﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Utilitaires;
using USB_HID;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace RBC9___HID
{



    public partial class FormHID : Form
    {
       MX1000 MyMX1000 = new MX1000();
       SpaceNavigator myNav;

        private int NumIco = 0;
        private System.Drawing.Icon[] MyIcon = new Icon[5];

        private void Icon_Init()
        {
            System.Reflection.Assembly MyAssembly = System.Reflection.Assembly.GetExecutingAssembly();
            MyIcon[0] = new System.Drawing.Icon(MyAssembly.GetManifestResourceStream("RBC9___HID.iconStop.ico"));
            MyIcon[1] = new System.Drawing.Icon(MyAssembly.GetManifestResourceStream("RBC9___HID.icon2.ico"));
            MyIcon[2] = new System.Drawing.Icon(MyAssembly.GetManifestResourceStream("RBC9___HID.icon3.ico"));
            MyIcon[3] = new System.Drawing.Icon(MyAssembly.GetManifestResourceStream("RBC9___HID.icon4.ico"));
            MyIcon[4] = new System.Drawing.Icon(MyAssembly.GetManifestResourceStream("RBC9___HID.icon1.ico"));

            Icon_Draw(0);

        }

        private void Icon_Bcl()
        {
            if (++NumIco > 4)
            {
                NumIco = 1;
            }
            Icon_Draw(NumIco);
        }

        private void Icon_Draw(int vNumIco)
        {
            notifyIcon.Icon = MyIcon[vNumIco];
        }

        private void SwitchMin(bool vUsbMin)
        {

            if (vUsbMin)
            {
                this.Hide();
                MenuNotify.MenuItems[1].Text = "Show";

            }
            else
            {

                this.Show();
                this.Activate();
                this.Focus();
                MenuNotify.MenuItems[1].Text = "Hide";

            }

        }

        public FormHID()
        {
            InitializeComponent();

            Icon_Init();

        }


        private void IconTimer_Tick(object sender, EventArgs e)
        {
            bool AnimIcon = false;

            MenuNotify.MenuItems[0].Checked = MyMX1000.AutoApply;
            if (MyMX1000.Profil != "")
            {
                MenuNotify.MenuItems[0].Text = "MX 1000 (" + MyMX1000.Profil + ")";
                AnimIcon = true;
            }
            else
            {
                MenuNotify.MenuItems[0].Text = "MX 1000";

            }

            if (AnimIcon)
                Icon_Bcl();
            else
                Icon_Draw(0);
        }


        private void menu_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            bool CurVis = this.Visible;

            SwitchMin(CurVis);
        }

        private void FormHID_Load(object sender, EventArgs e)
        {
            demar();
        }

        private void FormHID_Activated(object sender, EventArgs e)
        {
            
        }

        private void menu_Config_Click(object sender, EventArgs e)
        {
            bool CurVis = this.Visible;

            SwitchMin(CurVis);
        }

        private void menuItem1_Click(object sender, EventArgs e)
        {
            ParamMX1000 MyParam = new ParamMX1000();
            MyMX1000.Stop();
            MyParam.ShowDialog();
            MyMX1000.Start();
        }

        void myNav_OnButtonChanged(object sender, HIDChangedEventArgs args)
        {

            CheckForIllegalCrossThreadCalls = false;

            textBox1.Text = args.HIDValue.Axe[0].State_Current.ToString();
            textBox2.Text = args.HIDValue.Axe[1].State_Current.ToString();
            textBox3.Text = args.HIDValue.Axe[2].State_Current.ToString();
            textBox4.Text = args.HIDValue.Axe[3].State_Current.ToString();
            textBox5.Text = args.HIDValue.Axe[4].State_Current.ToString();
            textBox6.Text = args.HIDValue.Axe[5].State_Current.ToString();

            textBox7.Text = args.HIDValue.Btn[0].State_Current.ToString();
            textBox8.Text = args.HIDValue.Btn[1].State_Current.ToString();

     /*       newJoy.SetAnalog(args.HIDValue.Axe[0].State_Current, 0);
            newJoy.SetAnalog(args.HIDValue.Axe[1].State_Current, 1);
            newJoy.SetAnalog(args.HIDValue.Axe[2].State_Current, 2);
            newJoy.SetAnalog(args.HIDValue.Axe[3].State_Current, 3);
            newJoy.SetAnalog(args.HIDValue.Axe[4].State_Current, 4);
            newJoy.SetAnalog(args.HIDValue.Axe[5].State_Current, 5);

            newJoy.SetDigital(args.HIDValue.Btn[0].State_Current, 0);
            newJoy.SetDigital(args.HIDValue.Btn[0].State_Current, 1);

            newJoy.SetDigital(args.HIDValue.Btn[1].State_Current, 8);
            newJoy.SetDigital(args.HIDValue.Btn[1].State_Current, 9);
        
            newJoy.SendData();
     
            myMouse.Mouse_SetScroll(-args.HIDValue.Axe[5].State_Current);
*/
           // myMouse.Mouse_SetMove(args.HIDValue.Axe[0].State_Current, args.HIDValue.Axe[1].State_Current);
      //      myMouse.Mouse_SetMove(-args.HIDValue.Axe[4].State_Current, args.HIDValue.Axe[3].State_Current);
  
            
            if (args.HIDValue.Btn[0].State_Changed)
            {
               if (args.HIDValue.Btn[0].State_Current)
                {
                    //Send_Keyb_Mouse.Key_Down(66);
                 //   myMouse.Mouse_Clic_Left(true);
                }
                else
                {
                 //   myMouse.Mouse_Clic_Left(false);
                   // Send_Keyb_Mouse.Key_Up(66);
                }
            }

            if (args.HIDValue.Btn[1].State_Changed)
            {

                if (args.HIDValue.Btn[1].State_Current)
                {
                    
               
                }
                else
                {
                    
                }
            }
            
            //throw new Exception("The method or operation is not implemented.");
        }



        void demar()
        {
            myNav = null;
            myNav = SpaceNavigator.FindSpaceNav();
            if (myNav != null)
            {
                myNav.OnButtonChanged += new HIDChangedEventHandler(myNav_OnButtonChanged);
            }
        }
     
        private void FormHID_FormClosing(object sender, FormClosingEventArgs e)
        {
     
        }

     
      
        [DllImport("USER32.DLL")]
        public static extern IntPtr GetForegroundWindow();
  
        [DllImport("user32.dll")]
       private static extern int GetWindowThreadProcessId(IntPtr hWnd,  ref int pptt);

        private void button3_Click(object sender, EventArgs e)
        {
           myNav.SetLights(0x00);

          
         /*  
            Process tmpProc; 
            int nThisProcessID = 0;
            while (true)
            {      
                GetWindowThreadProcessId(GetForegroundWindow(), ref nThisProcessID);
                tmpProc = Process.GetProcessById(nThisProcessID);
                Debug.WriteLine(tmpProc.MainModule.ModuleName);
                Thread.Sleep(1000);
            }
            */
        }

        [DllImport("user32.dll")]
        extern static uint MapVirtualKeyA(uint uCode, uint uMapType);


    }
}﻿namespace RBC9___HID
{
    partial class FormHID
    {
        /// <summary>
        /// Variable nécessaire au concepteur.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Nettoyage des ressources utilisées.
        /// </summary>
        /// <param name="disposing">true si les ressources managées doivent être supprimées ; sinon, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Code généré par le Concepteur Windows Form

        /// <summary>
        /// Méthode requise pour la prise en charge du concepteur - ne modifiez pas
        /// le contenu de cette méthode avec l'éditeur de code.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormHID));
            this.notifyIcon = new System.Windows.Forms.NotifyIcon(this.components);
            this.MenuNotify = new System.Windows.Forms.ContextMenu();
            this.menuItem1 = new System.Windows.Forms.MenuItem();
            this.menu_Config = new System.Windows.Forms.MenuItem();
            this.menuItem2 = new System.Windows.Forms.MenuItem();
            this.menu_Close = new System.Windows.Forms.MenuItem();
            this.IconTimer = new System.Windows.Forms.Timer(this.components);
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.textBox3 = new System.Windows.Forms.TextBox();
            this.textBox4 = new System.Windows.Forms.TextBox();
            this.textBox5 = new System.Windows.Forms.TextBox();
            this.textBox6 = new System.Windows.Forms.TextBox();
            this.textBox7 = new System.Windows.Forms.TextBox();
            this.textBox8 = new System.Windows.Forms.TextBox();
            this.button3 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // notifyIcon
            // 
            this.notifyIcon.ContextMenu = this.MenuNotify;
            this.notifyIcon.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon.Icon")));
            this.notifyIcon.Text = "RBC9 HID";
            this.notifyIcon.Visible = true;
            this.notifyIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.notifyIcon_MouseDoubleClick);
            // 
            // MenuNotify
            // 
            this.MenuNotify.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItem1,
            this.menu_Config,
            this.menuItem2,
            this.menu_Close});
            // 
            // menuItem1
            // 
            this.menuItem1.Checked = true;
            this.menuItem1.Index = 0;
            this.menuItem1.Text = "MX 1000";
            this.menuItem1.Click += new System.EventHandler(this.menuItem1_Click);
            // 
            // menu_Config
            // 
            this.menu_Config.Index = 1;
            this.menu_Config.Text = "Config";
            this.menu_Config.Click += new System.EventHandler(this.menu_Config_Click);
            // 
            // menuItem2
            // 
            this.menuItem2.Index = 2;
            this.menuItem2.Text = "-";
            // 
            // menu_Close
            // 
            this.menu_Close.Index = 3;
            this.menu_Close.Text = "Close";
            this.menu_Close.Click += new System.EventHandler(this.menu_Close_Click);
            // 
            // IconTimer
            // 
            this.IconTimer.Enabled = true;
            this.IconTimer.Interval = 50;
            this.IconTimer.Tick += new System.EventHandler(this.IconTimer_Tick);
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(58, 202);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(102, 20);
            this.textBox1.TabIndex = 5;
            // 
            // textBox2
            // 
            this.textBox2.Location = new System.Drawing.Point(58, 219);
            this.textBox2.Name = "textBox2";
            this.textBox2.Size = new System.Drawing.Size(102, 20);
            this.textBox2.TabIndex = 6;
            // 
            // textBox3
            // 
            this.textBox3.Location = new System.Drawing.Point(58, 237);
            this.textBox3.Name = "textBox3";
            this.textBox3.Size = new System.Drawing.Size(102, 20);
            this.textBox3.TabIndex = 7;
            // 
            // textBox4
            // 
            this.textBox4.Location = new System.Drawing.Point(166, 202);
            this.textBox4.Name = "textBox4";
            this.textBox4.Size = new System.Drawing.Size(102, 20);
            this.textBox4.TabIndex = 8;
            // 
            // textBox5
            // 
            this.textBox5.Location = new System.Drawing.Point(166, 217);
            this.textBox5.Name = "textBox5";
            this.textBox5.Size = new System.Drawing.Size(102, 20);
            this.textBox5.TabIndex = 9;
            // 
            // textBox6
            // 
            this.textBox6.Location = new System.Drawing.Point(166, 236);
            this.textBox6.Name = "textBox6";
            this.textBox6.Size = new System.Drawing.Size(102, 20);
            this.textBox6.TabIndex = 10;
            // 
            // textBox7
            // 
            this.textBox7.Location = new System.Drawing.Point(324, 201);
            this.textBox7.Name = "textBox7";
            this.textBox7.Size = new System.Drawing.Size(102, 20);
            this.textBox7.TabIndex = 11;
            // 
            // textBox8
            // 
            this.textBox8.Location = new System.Drawing.Point(324, 222);
            this.textBox8.Name = "textBox8";
            this.textBox8.Size = new System.Drawing.Size(102, 20);
            this.textBox8.TabIndex = 12;
            // 
            // button3
            // 
            this.button3.Location = new System.Drawing.Point(544, 403);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(156, 32);
            this.button3.TabIndex = 27;
            this.button3.Text = "button3";
            this.button3.UseVisualStyleBackColor = true;
            this.button3.Click += new System.EventHandler(this.button3_Click);
            // 
            // FormHID
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(725, 512);
            this.ControlBox = false;
            this.Controls.Add(this.button3);
            this.Controls.Add(this.textBox8);
            this.Controls.Add(this.textBox7);
            this.Controls.Add(this.textBox6);
            this.Controls.Add(this.textBox5);
            this.Controls.Add(this.textBox4);
            this.Controls.Add(this.textBox3);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.textBox1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.Name = "FormHID";
            this.Opacity = 0.9;
            this.ShowInTaskbar = false;
            this.Text = "RBC9 - SpaceNavigator";
            this.Activated += new System.EventHandler(this.FormHID_Activated);
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FormHID_FormClosing);
            this.Load += new System.EventHandler(this.FormHID_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.NotifyIcon notifyIcon;
        private System.Windows.Forms.ContextMenu MenuNotify;
        private System.Windows.Forms.MenuItem menu_Config;
        private System.Windows.Forms.MenuItem menuItem2;
        private System.Windows.Forms.MenuItem menu_Close;
        private System.Windows.Forms.Timer IconTimer;
        private System.Windows.Forms.MenuItem menuItem1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.TextBox textBox2;
        private System.Windows.Forms.TextBox textBox3;
        private System.Windows.Forms.TextBox textBox4;
        private System.Windows.Forms.TextBox textBox5;
        private System.Windows.Forms.TextBox textBox6;
        private System.Windows.Forms.TextBox textBox7;
        private System.Windows.Forms.TextBox textBox8;
        private System.Windows.Forms.Button button3;
    }
}

using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using Utilitaires;
using System.Diagnostics;
using Microsoft.Win32;



namespace RBC9___HID
{

    class BaseLst
    {
        private string _Txt;
        private object _Id;

        public BaseLst(string Txt, object Id)
        {
            this._Txt = Txt;
            this._Id = Id;

        }
        public string Txt
        {
            get { return _Txt; }
            set { _Txt = value; }
        }
        public object Id
        {
            get { return _Id; }
            set { _Id = value; }
        }

        public override string ToString()
        {
            return Txt;
        }
    }

    class MyConst
    {

        public const int NAV_MAX_VALUE = 360;
        public const byte KEY_BTN = 0x01;
        public const byte KEY_KEEP = 0x02;
        public const byte KEY_RELEASE = 0x04;
        public const byte KEY_REPEAT = 0x10;

        public const int LEN_COMMENT = 44;

        static public string BaseKey = "System\\ControlSet001\\Services\\RBC9SpaceNavigator\\Layout";

        static public ArrayList MyDevice_Txt = new ArrayList();

        static public ArrayList MyBindFrom_AxePart_Txt = new ArrayList();

        static public ArrayList MyBindFrom_FromType_Txt = new ArrayList();

        static public ArrayList MyBindTo_Txt = new ArrayList();

        static public ArrayList MyBindTo_JoyAxe_Txt = new ArrayList();
        static public ArrayList MyBindTo_JoyBtn_Txt = new ArrayList();
        static public ArrayList MyBindTo_JoyPov_Txt = new ArrayList();

        static public ArrayList MyBindTo_MouBtn_Txt = new ArrayList();

        static public ArrayList MyBindTo_Key_Txt = new ArrayList();
        static public ArrayList MyBindTo_KeyCode_Txt = new ArrayList();
        static public ArrayList MyBindTo_KeyWWW_Txt = new ArrayList();


        static public string MyTxt_ById(ArrayList MyArray, object Id)
        {
            foreach (BaseLst MyTxt in MyArray)
            {
                if (MyTxt.Id.Equals(Id))
                {
                    return MyTxt.Txt;
                }
            }
            return null;
        }

        static MyConst()
        {
            ModifyRegistry myRegistry = new ModifyRegistry();
            myRegistry.BaseRegistryKey = Registry.LocalMachine;
            myRegistry.SubKey = "System\\Select";
            BaseKey = "System\\ControlSet" + myRegistry.ReadInt32("Current").ToString("000") + "\\Services\\RBC9SpaceNavigator\\Layout";


            MyDevice_Txt.Add(new BaseLst("SpaceNavigator", (int) 0xC626));
            MyDevice_Txt.Add(new BaseLst("SpacePilot", (int) 0xC625));
            MyDevice_Txt.Add(new BaseLst("SpaceTraveler", (int)0xC623));
            MyDevice_Txt.Add(new BaseLst("SpaceBall", (int)0xC621));

            MyBindTo_Txt.Add(new BaseLst("New Bind", BIND_TO.BIND_TO_NOBIND));
            MyBindTo_Txt.Add(new BaseLst("Joy Axe", BIND_TO.BIND_TO_JOYSTICK_AXE));
            MyBindTo_Txt.Add(new BaseLst("Joy Btn", BIND_TO.BIND_TO_JOYSTICK_BTN));
            MyBindTo_Txt.Add(new BaseLst("Joy POV", BIND_TO.BIND_TO_JOYSTICK_POV));
            MyBindTo_Txt.Add(new BaseLst("Mouse X", BIND_TO.BIND_TO_MOUSE_X));
            MyBindTo_Txt.Add(new BaseLst("Mouse Y", BIND_TO.BIND_TO_MOUSE_Y));
            MyBindTo_Txt.Add(new BaseLst("Mouse Wheel", BIND_TO.BIND_TO_MOUSE_WHEEL));
            MyBindTo_Txt.Add(new BaseLst("Mouse Btn", BIND_TO.BIND_TO_MOUSE_BTN));
            MyBindTo_Txt.Add(new BaseLst("Keyboard", BIND_TO.BIND_TO_KEYB));
            MyBindTo_Txt.Add(new BaseLst("Special Key", BIND_TO.BIND_TO_WWW));
            MyBindTo_Txt.Add(new BaseLst("Switch Layout", BIND_TO.BIND_TO_PROFIL));
            // MyBindTo_Txt.Add(new BaseLst("BIND_TO_TEST", BIND_TO.BIND_TO_TEST));


            MyBindTo_JoyAxe_Txt.Add(new BaseLst("X", (byte)0));
            MyBindTo_JoyAxe_Txt.Add(new BaseLst("Y", (byte)1));
            MyBindTo_JoyAxe_Txt.Add(new BaseLst("Z", (byte)2));
            MyBindTo_JoyAxe_Txt.Add(new BaseLst("rX", (byte)3));
            MyBindTo_JoyAxe_Txt.Add(new BaseLst("rY", (byte)4));
            MyBindTo_JoyAxe_Txt.Add(new BaseLst("rZ", (byte)5));
            MyBindTo_JoyAxe_Txt.Add(new BaseLst("Slider", (byte)6));
            MyBindTo_JoyAxe_Txt.Add(new BaseLst("Slider2", (byte)7));
          //  MyBindTo_JoyAxe_Txt.Add(new BaseLst("Throttle", (byte)8));


            MyBindFrom_AxePart_Txt.Add(new BaseLst("Full Axe", SEMI_AXE.AXE_ALL));
            MyBindFrom_AxePart_Txt.Add(new BaseLst("Semi Axe  > 0", SEMI_AXE.AXE_POS));
            MyBindFrom_AxePart_Txt.Add(new BaseLst("Semi Axe  < 0", SEMI_AXE.AXE_NEG));

            MyBindFrom_FromType_Txt.Add(new BaseLst("Standart", PRESS_TYPE.PRESS_STD));
            MyBindFrom_FromType_Txt.Add(new BaseLst("Short Press", PRESS_TYPE.PRESS_SHORT));
            MyBindFrom_FromType_Txt.Add(new BaseLst("Long Press", PRESS_TYPE.PRESS_LONG));


            MyBindTo_JoyPov_Txt.Add(new BaseLst("Up / Down", BIND_POV.POV_VERT));
            MyBindTo_JoyPov_Txt.Add(new BaseLst("Left / Right", BIND_POV.POV_HORI));


            MyBindTo_JoyBtn_Txt.Add(new BaseLst("1", (byte)0));
            MyBindTo_JoyBtn_Txt.Add(new BaseLst("2", (byte)1));
            MyBindTo_JoyBtn_Txt.Add(new BaseLst("3", (byte)2));
            MyBindTo_JoyBtn_Txt.Add(new BaseLst("4", (byte)3));
            MyBindTo_JoyBtn_Txt.Add(new BaseLst("5", (byte)4));
            MyBindTo_JoyBtn_Txt.Add(new BaseLst("6", (byte)5));
            MyBindTo_JoyBtn_Txt.Add(new BaseLst("7", (byte)6));
            MyBindTo_JoyBtn_Txt.Add(new BaseLst("8", (byte)7));

            MyBindTo_MouBtn_Txt.Add(new BaseLst("Left", (byte)0));
            MyBindTo_MouBtn_Txt.Add(new BaseLst("Right", (byte)1));
            MyBindTo_MouBtn_Txt.Add(new BaseLst("Middle", (byte)2));
            MyBindTo_MouBtn_Txt.Add(new BaseLst("Mouse 4", (byte)3));
            MyBindTo_MouBtn_Txt.Add(new BaseLst("Mouse 5", (byte)4));


            MyBindTo_Key_Txt.Add(new BaseLst("Key Press", (byte)KEY_BTN));
            MyBindTo_Key_Txt.Add(new BaseLst("Key Hold", (byte)KEY_KEEP));
            MyBindTo_Key_Txt.Add(new BaseLst("Key Release", (byte)KEY_RELEASE));

            {
                MyBindTo_KeyCode_Txt.Add(new BaseLst("", (byte)0x00));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("a / A", (byte)0x04));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("b / B", (byte)0x05));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("c / C", (byte)0x06));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("d / D", (byte)0x07));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("e / E", (byte)0x08));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("f / F", (byte)0x09));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("g / G", (byte)0x0a));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("h / H", (byte)0x0b));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("i / I", (byte)0x0c));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("j / J", (byte)0x0d));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("k / K", (byte)0x0e));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("l / L", (byte)0x0f));

                MyBindTo_KeyCode_Txt.Add(new BaseLst("m / M", (byte)0x10));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("n / N", (byte)0x11));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("o / O", (byte)0x12));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("p / P", (byte)0x13));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("q / Q", (byte)0x14));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("r / R", (byte)0x15));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("s / S", (byte)0x16));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("t / T", (byte)0x17));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("u / U", (byte)0x18));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("v / V", (byte)0x19));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("w / W", (byte)0x1a));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("x / X", (byte)0x1b));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("y / Y", (byte)0x1c));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("z / Z", (byte)0x1d));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("1", (byte)0x1e));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("2", (byte)0x1f));

                MyBindTo_KeyCode_Txt.Add(new BaseLst("3", (byte)0x20));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("4", (byte)0x21));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("5", (byte)0x22));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("6", (byte)0x23));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("7", (byte)0x24));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("8", (byte)0x25));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("9", (byte)0x26));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("0", (byte)0x27));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Enter", (byte)0x28));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Esc", (byte)0x29));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Back Space", (byte)0x2a));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Tab", (byte)0x2b));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Space", (byte)0x2c));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("- / _", (byte)0x2d));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("= / +", (byte)0x2e));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("[ / {", (byte)0x2f));

                MyBindTo_KeyCode_Txt.Add(new BaseLst("] / }", (byte)0x30));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("\\ / |", (byte)0x31));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Non-US # / ~", (byte)0x32));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("; / :", (byte)0x33));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("\x91 / \x93", (byte)0x34));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Grave Accent / Tilde", (byte)0x35));
                MyBindTo_KeyCode_Txt.Add(new BaseLst(", / <", (byte)0x36));
                MyBindTo_KeyCode_Txt.Add(new BaseLst(". / >", (byte)0x37));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("/ / ?", (byte)0x38));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Caps Lock", (byte)0x39));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("F1", (byte)0x3a));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("F2", (byte)0x3b));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("F3", (byte)0x3c));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("F4", (byte)0x3d));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("F5", (byte)0x3e));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("F6", (byte)0x3f));

                MyBindTo_KeyCode_Txt.Add(new BaseLst("F7", (byte)0x40));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("F8", (byte)0x41));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("F9", (byte)0x42));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("F10", (byte)0x43));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("F11", (byte)0x44));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("F12", (byte)0x45));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Print Screen", (byte)0x46));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Scroll Lock", (byte)0x47));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Pause", (byte)0x48));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Insert", (byte)0x49));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Home", (byte)0x4a));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Page Up", (byte)0x4b));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Delete", (byte)0x4c));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("End", (byte)0x4d));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Page Down", (byte)0x4e));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Right Arrow", (byte)0x4f));

                MyBindTo_KeyCode_Txt.Add(new BaseLst("Left Arrow", (byte)0x50));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Down Arrow", (byte)0x51));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Up Arrow", (byte)0x52));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Keypad Num Lock / Clear", (byte)0x53));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Keypad /", (byte)0x54));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Keypad *", (byte)0x55));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Keypad -", (byte)0x56));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Keypad +", (byte)0x57));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Keypad Enter", (byte)0x58));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Keypad 1 / End", (byte)0x59));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Keypad 2 / Down Arrow", (byte)0x5a));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Keypad 3 / Page Down", (byte)0x5b));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Keypad 4 / Left Arrow", (byte)0x5c));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Keypad 5", (byte)0x5d));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Keypad 6 / Right Arrow", (byte)0x5e));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Keypad 7 / Home", (byte)0x5f));

                MyBindTo_KeyCode_Txt.Add(new BaseLst("Keypad 8 / Up Arrow", (byte)0x60));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Keypad 9 / Page Up", (byte)0x61));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Keypad 0 / Insert", (byte)0x62));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Keypad . / Delete", (byte)0x63));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Non-US \\ / |", (byte)0x64));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Application", (byte)0x65));
             

                MyBindTo_KeyCode_Txt.Add(new BaseLst("Left Control", (byte)0xe0));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Left Shift", (byte)0xe1));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Left Alt", (byte)0xe2));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Left GUI", (byte)0xe3));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Right Control", (byte)0xe4));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Right Shift", (byte)0xe5));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Right Alt", (byte)0xe6));
                MyBindTo_KeyCode_Txt.Add(new BaseLst("Right GUI", (byte)0xe7));

            }

            {

                MyBindTo_KeyWWW_Txt.Add(new BaseLst("Mute", (byte)0x01));
                MyBindTo_KeyWWW_Txt.Add(new BaseLst("Volume Up", (byte)0x02));
                MyBindTo_KeyWWW_Txt.Add(new BaseLst("Volume Down", (byte)0x03));
                MyBindTo_KeyWWW_Txt.Add(new BaseLst("Play/Pause", (byte)0x04));
                MyBindTo_KeyWWW_Txt.Add(new BaseLst("Stop", (byte)0x05));
                MyBindTo_KeyWWW_Txt.Add(new BaseLst("Previous Track", (byte)0x06));
                MyBindTo_KeyWWW_Txt.Add(new BaseLst("Next Track", (byte)0x07));
                MyBindTo_KeyWWW_Txt.Add(new BaseLst("Calculator", (byte)0x09));
                MyBindTo_KeyWWW_Txt.Add(new BaseLst("Mail", (byte)0x08));
                MyBindTo_KeyWWW_Txt.Add(new BaseLst("www search", (byte)0x0A));
                MyBindTo_KeyWWW_Txt.Add(new BaseLst("www home", (byte)0x0B));
                MyBindTo_KeyWWW_Txt.Add(new BaseLst("www favorites", (byte)0x0C));
                MyBindTo_KeyWWW_Txt.Add(new BaseLst("www refresh", (byte)0x0D));
                MyBindTo_KeyWWW_Txt.Add(new BaseLst("www stop", (byte)0x0E));
                MyBindTo_KeyWWW_Txt.Add(new BaseLst("www forward", (byte)0x0F));
                MyBindTo_KeyWWW_Txt.Add(new BaseLst("www back", (byte)0x10));

            }

        }

    }

    public enum BIND_FROM
    {
        BIND_FROM_AXE,
        BIND_FROM_BTN,
    } ;

    public enum SEMI_AXE
    {
        AXE_ALL = 0,
        AXE_POS,
        AXE_NEG,
    };

    public enum PRESS_TYPE
    {
        PRESS_STD=0,
	    PRESS_SHORT,
	    PRESS_LONG,
    };

 
    public enum BIND_TO
    {
        BIND_TO_NOBIND = 0,
        BIND_TO_JOYSTICK_AXE,
        BIND_TO_JOYSTICK_BTN,
        BIND_TO_JOYSTICK_POV,
        BIND_TO_MOUSE_X,
        BIND_TO_MOUSE_Y,
        BIND_TO_MOUSE_WHEEL,
        BIND_TO_MOUSE_BTN,
        BIND_TO_KEYB,
        BIND_TO_PROFIL,
        BIND_TO_WWW,

    } ;


    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct NAVAXE
    {
        public byte NumAxe;
        public byte Invert;
        public short DeadZone;
        public short MinVal;
        public short MaxVal;
        public SEMI_AXE AxePart;
    };

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct NAVBTN
    {
        public byte NumBtn;
        public byte Invert;
        public short FalseVal;
        public short TrueVal;
    } ;

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct FROMTYPE
    {
        public short Delay;
        public PRESS_TYPE Type;
    } ;

    public enum BIND_POV
    {
        POV_VERT,
        POV_HORI,

    } ;

    [StructLayout(LayoutKind.Explicit, Pack = 1)]
    public struct JOY_BIND
    {
        [FieldOffset(0)]
        public byte Axe;
        [FieldOffset(0)]
        public byte Btn;
        [FieldOffset(0)]
        public BIND_POV POV;
    } ;

    [StructLayout(LayoutKind.Explicit, Pack = 1)]
    public struct MOU_BIND
    {
        [FieldOffset(0)]
        public byte Sensi;
        [FieldOffset(0)]
        public byte Wheel_Speed;
        [FieldOffset(0)]
        public byte Btn;
    } ;

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct KEY_BIND
    {
        public byte Event;
        public short FireDelay;

        public byte Code1;
        public byte Code2;
        public byte Code3;
        public byte Code4;
        public byte Code5;


    } ;


    [StructLayout(LayoutKind.Explicit, Pack = 1)]
    public unsafe struct BIND_STRUCT
    {

        [FieldOffset(0)]
        public BIND_FROM BindFrom;

        [FieldOffset(4)]
        public NAVAXE FromAxe;
        [FieldOffset(4)]
        public NAVBTN FromBtn;

        [FieldOffset(16)]
        public BIND_TO BindTo;

        [FieldOffset(20)]
        public JOY_BIND Joy;
        [FieldOffset(20)]
        public MOU_BIND Mou;
        [FieldOffset(20)]
        public KEY_BIND Key;
        [FieldOffset(20)]
        public short Profil_Id;
        [FieldOffset(20)]
        public byte www;

        [FieldOffset(28)]
        public FROMTYPE FromType;

        [FieldOffset(40)]
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = MyConst.LEN_COMMENT)]
        public char[] Comment;

    };

    class LayoutBind
    {
        private BIND_STRUCT BindToDo = new BIND_STRUCT();

        public LayoutBind(BIND_FROM BindFrom, byte BindFromNum, BIND_TO BindTo)
        {
            this.BindFrom = BindFrom;
            this.BindFromNum = BindFromNum;
            this.BindTo = BindTo;
            this.Comment = "";
        }
        public LayoutBind(BIND_FROM BindFrom, byte BindFromNum)
        {
            this.BindFrom = BindFrom;
            this.BindFromNum = BindFromNum;
            this.BindTo = BIND_TO.BIND_TO_NOBIND;
            this.Comment = "";
        }

        public LayoutBind(byte[] ByteStruct)
        {
            

            BindByte = ByteStruct;
        }

        public byte[] BindByte
        {
            get
            {

                byte[] buffer = new byte[Marshal.SizeOf(BindToDo)];

                GCHandle h = GCHandle.Alloc(buffer, GCHandleType.Pinned);

                Marshal.StructureToPtr(BindToDo, h.AddrOfPinnedObject(), false);

                h.Free();
                
                return buffer;
            }

            set
            {
                GCHandle h = GCHandle.Alloc(value, GCHandleType.Pinned);

                BindToDo = (BIND_STRUCT)Marshal.PtrToStructure(h.AddrOfPinnedObject(), typeof(BIND_STRUCT));

                h.Free();
                if (value.Length < Marshal.SizeOf(typeof(BIND_STRUCT)))
                {
                    this.Comment = "";
                }

            }
        }

        public String Comment
        {
           get
            {
                GCHandle h = GCHandle.Alloc(BindToDo.Comment, GCHandleType.Pinned);

              
                string Retour = (string)Marshal.PtrToStringUni(h.AddrOfPinnedObject());

                h.Free();

                return Retour;
            }

            set
            {
                if (BindToDo.Comment == null)
                {
                    BindToDo.Comment = new char[MyConst.LEN_COMMENT];
                }

                for (int i = 0; i < BindToDo.Comment.Length; BindToDo.Comment[i++] = '\0') ;
                    
                value.ToCharArray(0, value.Length < MyConst.LEN_COMMENT ? value.Length : MyConst.LEN_COMMENT).CopyTo(BindToDo.Comment, 0);

                
            }
        }

        public BIND_FROM BindFrom
        {
            get { return BindToDo.BindFrom; }
            set
            {

                BindToDo.BindFrom = value;
               
                FromType = PRESS_TYPE.PRESS_STD;
 
                switch (BindToDo.BindFrom)
                {
                    case BIND_FROM.BIND_FROM_AXE:
                        BindToDo.FromAxe.NumAxe = 0;
                        BindToDo.FromAxe.Invert = 0;
                        BindToDo.FromAxe.DeadZone = 0;
                        BindToDo.FromAxe.MinVal = 0;
                        BindToDo.FromAxe.MaxVal = MyConst.NAV_MAX_VALUE;
                        BindToDo.FromAxe.AxePart = SEMI_AXE.AXE_ALL;
                        break;

                    case BIND_FROM.BIND_FROM_BTN:
                        BindToDo.FromBtn.NumBtn = 0;
                        BindToDo.FromBtn.Invert = 0;
                        BindToDo.FromBtn.FalseVal = 0;
                        BindToDo.FromBtn.TrueVal = MyConst.NAV_MAX_VALUE;
                        break;
                }
            }
        }

        public byte BindFromNum
        {
            get
            {
                switch (BindToDo.BindFrom)
                {
                    case BIND_FROM.BIND_FROM_AXE:
                        return BindToDo.FromAxe.NumAxe;


                    case BIND_FROM.BIND_FROM_BTN:
                        return BindToDo.FromBtn.NumBtn;
                }
                return 0;
            }


            set
            {
                switch (BindToDo.BindFrom)
                {
                    case BIND_FROM.BIND_FROM_AXE:
                        BindToDo.FromAxe.NumAxe = value;
                        break;

                    case BIND_FROM.BIND_FROM_BTN:
                        BindToDo.FromBtn.NumBtn = value;
                        break;
                }

            }

        }
        public byte Invert
        {
            get
            {
                switch (BindToDo.BindFrom)
                {
                    case BIND_FROM.BIND_FROM_AXE:
                        return BindToDo.FromAxe.Invert;


                    case BIND_FROM.BIND_FROM_BTN:
                        return BindToDo.FromBtn.Invert;
                }
                return 0;
            }


            set
            {
                switch (BindToDo.BindFrom)
                {
                    case BIND_FROM.BIND_FROM_AXE:
                        BindToDo.FromAxe.Invert = value;
                        break;

                    case BIND_FROM.BIND_FROM_BTN:
                        BindToDo.FromBtn.Invert = value;
                        break;
                }

            }
        }

        public short DeadZone
        {
            get
            {
                if (BindToDo.BindFrom == BIND_FROM.BIND_FROM_AXE)
                {
                    return BindToDo.FromAxe.DeadZone;
                }


                return 0;
            }


            set
            {
                short NewVal = value;
                if (NewVal > MyConst.NAV_MAX_VALUE)
                    NewVal = MyConst.NAV_MAX_VALUE;

                if (BindToDo.BindFrom == BIND_FROM.BIND_FROM_AXE)
                    BindToDo.FromAxe.DeadZone = NewVal;
            }
        }

        public short FromDelay
        {
            get
            {

                return BindToDo.FromType.Delay;

            }

            set
            {

                BindToDo.FromType.Delay = value;
            }
        }

        public short MinVal
        {
            get
            {
                switch (BindToDo.BindFrom)
                {
                    case BIND_FROM.BIND_FROM_AXE:
                        return BindToDo.FromAxe.MinVal;


                    case BIND_FROM.BIND_FROM_BTN:
                        return BindToDo.FromBtn.FalseVal;
                }
                return 0;
            }


            set
            {
                short NewVal = value;
                if (NewVal < 0)
                    NewVal = 0;
                if (NewVal > MyConst.NAV_MAX_VALUE)
                    NewVal = MyConst.NAV_MAX_VALUE;


                switch (BindToDo.BindFrom)
                {
                    case BIND_FROM.BIND_FROM_AXE:
                        BindToDo.FromAxe.MinVal = NewVal;
                        break;

                    case BIND_FROM.BIND_FROM_BTN:
                        BindToDo.FromBtn.FalseVal = NewVal;
                        break;
                }

            }
        }
        public short MaxVal
        {
            get
            {
                switch (BindToDo.BindFrom)
                {
                    case BIND_FROM.BIND_FROM_AXE:
                        return BindToDo.FromAxe.MaxVal;


                    case BIND_FROM.BIND_FROM_BTN:
                        return BindToDo.FromBtn.TrueVal;
                }
                return 0;
            }


            set
            {
                short NewVal = value;
                if (NewVal < 0)
                    NewVal = 0;
                if (NewVal > MyConst.NAV_MAX_VALUE)
                    NewVal = MyConst.NAV_MAX_VALUE;

                switch (BindToDo.BindFrom)
                {
                    case BIND_FROM.BIND_FROM_AXE:
                        BindToDo.FromAxe.MaxVal = NewVal;
                        break;

                    case BIND_FROM.BIND_FROM_BTN:
                        BindToDo.FromBtn.TrueVal = NewVal;
                        break;
                }

            }
        }
        public SEMI_AXE AxePart
        {
            get { return BindToDo.FromAxe.AxePart; }
            set { BindToDo.FromAxe.AxePart = value; }
        }

        public PRESS_TYPE FromType
        {
            get { return BindToDo.FromType.Type; }
            set {

                BindToDo.FromType.Type = value;
                if (BindToDo.FromType.Type == PRESS_TYPE.PRESS_STD)
                {
                    BindToDo.FromType.Delay = 0;
                }
                else
                {
                    BindToDo.FromType.Delay = 500;
                }
            
            }
        }

        public BIND_TO BindTo
        {
            get { return BindToDo.BindTo; }
            set
            {

                BindToDo.BindTo = value;

                switch (BindToDo.BindTo)
                {
                    case BIND_TO.BIND_TO_JOYSTICK_AXE:
                        BindToDo.Joy.Axe = 0;
                        break;
                    case BIND_TO.BIND_TO_JOYSTICK_BTN:
                        BindToDo.Joy.Btn = 0;
                        break;
                    case BIND_TO.BIND_TO_JOYSTICK_POV:
                        BindToDo.Joy.POV = BIND_POV.POV_VERT;
                        break;

                    case BIND_TO.BIND_TO_MOUSE_BTN:
                        BindToDo.Mou.Btn = 0;
                        break;

                    case BIND_TO.BIND_TO_MOUSE_X:
                        BindToDo.Mou.Sensi = 100;
                        break;

                    case BIND_TO.BIND_TO_MOUSE_Y:
                        BindToDo.Mou.Sensi = 100;
                        break;

                    case BIND_TO.BIND_TO_MOUSE_WHEEL:
                        BindToDo.Mou.Wheel_Speed = 100;
                        break;

                    case BIND_TO.BIND_TO_PROFIL:
                        BindToDo.Profil_Id = -1;
                        break;

                    case BIND_TO.BIND_TO_KEYB:
                        BindToDo.Key.Event = MyConst.KEY_BTN;
                        BindToDo.Key.FireDelay = 10;
                        BindToDo.Key.Code1 = 0;
                        BindToDo.Key.Code2 = 0;
                        BindToDo.Key.Code3 = 0;
                        BindToDo.Key.Code4 = 0;
                        BindToDo.Key.Code5 = 0;
                        break;

                    case BIND_TO.BIND_TO_WWW:
                        BindToDo.www = 0;
                        break;

                }
            }
        }

        public string BindTo_Txt
        {
            get
            {
                string TmpTxt = MyConst.MyTxt_ById(MyConst.MyBindTo_Txt, BindToDo.BindTo);

                switch (BindToDo.BindTo)
                {
                    case BIND_TO.BIND_TO_JOYSTICK_AXE:
                        TmpTxt = TmpTxt + " : " + MyConst.MyTxt_ById(MyConst.MyBindTo_JoyAxe_Txt, BindToDo.Joy.Axe);

                        break;
                    case BIND_TO.BIND_TO_JOYSTICK_BTN:
                        TmpTxt = TmpTxt + " : " + MyConst.MyTxt_ById(MyConst.MyBindTo_JoyBtn_Txt, BindToDo.Joy.Btn);
                        break;
                    case BIND_TO.BIND_TO_JOYSTICK_POV:
                        TmpTxt = TmpTxt + " : " + MyConst.MyTxt_ById(MyConst.MyBindTo_JoyPov_Txt, BindToDo.Joy.POV);
                        break;

                    case BIND_TO.BIND_TO_MOUSE_BTN:
                        TmpTxt = TmpTxt + " : " + MyConst.MyTxt_ById(MyConst.MyBindTo_MouBtn_Txt, BindToDo.Mou.Btn);
                        break;

                    case BIND_TO.BIND_TO_KEYB:
                        TmpTxt = TmpTxt + " : " + MyConst.MyTxt_ById(MyConst.MyBindTo_KeyCode_Txt, BindToDo.Key.Code1);
                        break;

                    case BIND_TO.BIND_TO_WWW:
                        TmpTxt = TmpTxt + " : " + MyConst.MyTxt_ById(MyConst.MyBindTo_KeyWWW_Txt, BindToDo.www);
                        break;

                }

                return TmpTxt;
            }
        }
        public byte BindTo_JoyAxe
        {
            get
            {
                if (BindToDo.BindTo != BIND_TO.BIND_TO_JOYSTICK_AXE)
                {
                    return 0;
                }


                return BindToDo.Joy.Axe;

            }
            set { BindToDo.Joy.Axe = value; }
        }
        public byte BindTo_JoyBtn
        {
            get
            {

                if (BindToDo.BindTo != BIND_TO.BIND_TO_JOYSTICK_BTN)
                {
                    return 0;
                }


                return BindToDo.Joy.Btn;


            }
            set { BindToDo.Joy.Btn = value; }
        }

        public byte BindTo_MouBtn
        {
            get
            {

                if (BindToDo.BindTo != BIND_TO.BIND_TO_MOUSE_BTN)
                {
                    return 0;
                }


                return BindToDo.Mou.Btn;

            }
            set { BindToDo.Mou.Btn = value; }
        }

        public byte BindTo_MouSensi
        {
            get
            {

                if ((BindToDo.BindTo != BIND_TO.BIND_TO_MOUSE_X)
                    && (BindToDo.BindTo != BIND_TO.BIND_TO_MOUSE_Y)
                    && (BindToDo.BindTo != BIND_TO.BIND_TO_MOUSE_WHEEL))
                {
                    return 0;
                }


                return BindToDo.Mou.Sensi;

            }
            set { BindToDo.Mou.Sensi = value; }
        }

        public BIND_POV BindTo_JoyPov
        {
            get
            {

                if (BindToDo.BindTo != BIND_TO.BIND_TO_JOYSTICK_POV)
                {
                    return BIND_POV.POV_VERT;
                }


                return BindToDo.Joy.POV;

            }
            set { BindToDo.Joy.POV = value; }
        }

        public short BindTo_ProfilId
        {
            get
            {

                if (BindToDo.BindTo != BIND_TO.BIND_TO_PROFIL)
                {
                    return 0;
                }


                return BindToDo.Profil_Id;


            }
            set { BindToDo.Profil_Id = value; }
        }


        public byte BindTo_Key
        {
            get
            {
                if (BindToDo.BindTo != BIND_TO.BIND_TO_KEYB)
                {
                    return MyConst.KEY_BTN;
                }


                return (byte)(BindToDo.Key.Event & 0x0f);
            }
            set
            {
                BindToDo.Key.Event &= 0xf0;

                BindToDo.Key.Event |= value;

            }
        }

        public bool BindTo_KeyRepeat
        {
            get
            {
                if (BindToDo.BindTo != BIND_TO.BIND_TO_KEYB)
                {
                    return false;
                }


                return (bool)((BindToDo.Key.Event & MyConst.KEY_REPEAT) == MyConst.KEY_REPEAT);
            }
            set
            {
                if (value)
                {
                    BindToDo.Key.Event |= MyConst.KEY_REPEAT;
                }
                else
                {

                    BindToDo.Key.Event &= 0x0f;
                }
            }
        }

        public short BindTo_KeyDelay
        {
            get
            {
                if (BindToDo.BindTo != BIND_TO.BIND_TO_KEYB)
                {
                    return 0;
                }


                return BindToDo.Key.FireDelay;
            }
            set
            {
                BindToDo.Key.FireDelay = value;
            }
        }

        public byte BindTo_Key1
        {
            get
            {
                if (BindToDo.BindTo != BIND_TO.BIND_TO_KEYB)
                {
                    return 0;
                }
                return BindToDo.Key.Code1;
            }
            set { BindToDo.Key.Code1 = value; }
        }

        public byte BindTo_Key2
        {
            get
            {
                if (BindToDo.BindTo != BIND_TO.BIND_TO_KEYB)
                {
                    return 0;
                }
                return BindToDo.Key.Code2;
            }
            set { BindToDo.Key.Code2 = value; }
        }

        public byte BindTo_Key3
        {
            get
            {
                if (BindToDo.BindTo != BIND_TO.BIND_TO_KEYB)
                {
                    return 0;
                }
                return BindToDo.Key.Code3;
            }
            set { BindToDo.Key.Code3 = value; }
        }

        public byte BindTo_Key4
        {
            get
            {
                if (BindToDo.BindTo != BIND_TO.BIND_TO_KEYB)
                {
                    return 0;
                }
                return BindToDo.Key.Code4;
            }
            set { BindToDo.Key.Code4 = value; }
        }

        public byte BindTo_Key5
        {
            get
            {
                if (BindToDo.BindTo != BIND_TO.BIND_TO_KEYB)
                {
                    return 0;
                }
                return BindToDo.Key.Code5;
            }
            set { BindToDo.Key.Code5 = value; }
        }


        public byte BindTo_WWW
        {
            get
            {
                if (BindToDo.BindTo != BIND_TO.BIND_TO_WWW)
                {
                    return 0;
                }
                return BindToDo.www;
            }
            set { BindToDo.www = value; }
        }
    }


    class LayoutStruct : IComparable 
    {

        private string _Profil_Name;
        private string _RegKey;
        private short _Profil_Id;
        private int _DeadZone;

        public ArrayList _Bind = new ArrayList();
        public ArrayList _AppAuto = new ArrayList();

        public LayoutStruct(string RegKey)
        {
            ReadLayout(RegKey, true);
        }

        public LayoutStruct(string RegKey, bool LoadBind)
        {
            ReadLayout(RegKey, LoadBind);
        }

        public LayoutStruct(short Profil_Id)
        {
            this.Profil_Name = "- New Layout -";
            this.DeadZone = 0;
            this.Profil_Id = Profil_Id;

        }

        public int CompareTo(object obj)
        {
            if (obj is LayoutStruct)
            {
                LayoutStruct temp = (LayoutStruct)obj;

                return _Profil_Name.CompareTo(temp._Profil_Name);
            }

            throw new ArgumentException("object is not a LayoutStruct");
        }


        private void ReadLayout(string RegKey, bool LoadBind)
        {
            string[] MyAppAutoLst;

            ModifyRegistry myRegistry = new ModifyRegistry();
            myRegistry.BaseRegistryKey = Registry.LocalMachine;
            myRegistry.SubKey = MyConst.BaseKey + "\\" + RegKey;

            this._RegKey = RegKey;

            this.Profil_Name = myRegistry.ReadString("Profil_Name");
            this.DeadZone = myRegistry.ReadInt32("DeadZone");
            this.Profil_Id = (short)myRegistry.ReadInt32("Profil_Id");
            MyAppAutoLst = (string[])myRegistry.Read("AppAuto");

            _AppAuto.Clear();
            if (MyAppAutoLst != null)
            {
                foreach (string MyAppAuto in MyAppAutoLst)
                {
                    _AppAuto.Add(new BaseLst(MyAppAuto, this.Profil_Id));
                }
            }

            if (LoadBind)
                ReadBind();
        }

        private void ReadBind()
        {

            ModifyRegistry myRegistry = new ModifyRegistry();

            myRegistry.BaseRegistryKey = Registry.LocalMachine;
            myRegistry.SubKey = MyConst.BaseKey + "\\" + _RegKey;

            _Bind.Clear();

            foreach (string BindName in myRegistry.ValueNames())
            {
                if (BindName.IndexOf("Bind - ") == 0)
                {
                    _Bind.Add(new LayoutBind(myRegistry.ReadBinary(BindName)));
                }
            }


        }

        public void ExportBind(string FileName)
        {
            int TailleBind = Marshal.SizeOf(typeof(BIND_STRUCT));
            byte[] buffer = new byte[_Bind.Count * TailleBind];
            int NumBind = 0;
         
            foreach (LayoutBind Bind in _Bind)
            {
                Array.Copy(Bind.BindByte, 0, buffer, NumBind * TailleBind, TailleBind);
                NumBind++;
            }
            File.WriteAllBytes(FileName, buffer);
        }


        public void ImportBind(string FileName)
        {
            int TailleBind = Marshal.SizeOf(typeof(BIND_STRUCT));
            byte[] buffer;
            int NumBind = 0;

            buffer = File.ReadAllBytes(FileName);
            if ((buffer.Length % TailleBind) != 0)
            {
                TailleBind = 34; // struct end  from type
                if ((buffer.Length % TailleBind) != 0)
                {
                    TailleBind = 30; // struct end www
                }
            }

            byte[] NewBind = new byte[TailleBind]; 

            if (buffer.Length <= 0) return;

            for (NumBind = 0; NumBind < buffer.Length / TailleBind; NumBind++)
            {
                 Array.Copy(buffer, NumBind * TailleBind, NewBind, 0, TailleBind);
                 _Bind.Add(new LayoutBind(NewBind));
            }
        }
        
        public void Save()
        {
            string[] MyAppAutoLst;
            int BclStr;
            int NumBind;

            ModifyRegistry myRegistry = new ModifyRegistry();
            myRegistry.BaseRegistryKey = Registry.LocalMachine;
            
            _RegKey = "Layout - " + Profil_Id.ToString("[0000]");

            myRegistry.SubKey = MyConst.BaseKey + "\\" + _RegKey;

            myRegistry.Write("Profil_Id", (Int32)_Profil_Id);
            myRegistry.Write("Profil_Name", _Profil_Name);
            myRegistry.Write("DeadZone", (Int32)_DeadZone);

            NumBind = 0;
            foreach (LayoutBind Bind in _Bind)
            {
                myRegistry.Write("Bind - " + NumBind.ToString("[0000]"), Bind.BindByte);
                NumBind++;
            }

            MyAppAutoLst = new string[_AppAuto.Count];
            BclStr = 0;
            foreach (BaseLst MyAppAuto in _AppAuto)
            {
                MyAppAutoLst[BclStr++] = MyAppAuto.Txt;
            }
            myRegistry.Write("AppAuto", MyAppAutoLst);
        }

        public string Profil_Name
        {
            get { return _Profil_Name; }
            set { _Profil_Name = value; }
        }

        public string RegKey
        {
            get { return _RegKey; }
            set { _RegKey = value; }
        }

        public short Profil_Id
        {
            get { return _Profil_Id; }
            set { _Profil_Id = value; }
        }

        public int DeadZone
        {
            get { return _DeadZone; }
            set
            {

                _DeadZone = value;

                if (_DeadZone < 0)
                    _DeadZone = 0;

                if (_DeadZone > MyConst.NAV_MAX_VALUE)
                    _DeadZone = MyConst.NAV_MAX_VALUE;


            }
        }

        public override string ToString()
        {
            return string.Format("[{0}] {1}", Profil_Id.ToString("0000"), _Profil_Name);
        }
    }

    class LayoutList
    {
        private short _Default_Profil;
        private bool _AutoSwitch;
        private bool _InfoBulle;
        private bool _StopIcon;
        private int _DeviceId;

        public ArrayList _Layout = new ArrayList();
        ModifyRegistry myRegistry = new ModifyRegistry();

        public LayoutList()
        {
            myRegistry.BaseRegistryKey = Registry.LocalMachine;
            myRegistry.SubKey = MyConst.BaseKey;

        }

        private short NexId()
        {
            short NewId = 1;
            foreach (LayoutStruct Layout in _Layout)
            {
                if (Layout.Profil_Id >= NewId)
                {
                    NewId = (short)(Layout.Profil_Id + 1);
                }
            }
            return NewId;
        }

        public int AddNewLayout()
        {

            return _Layout.Add(new LayoutStruct(NexId()));
            
        }

        public int Duplicate(LayoutStruct Source)
        {
            LayoutStruct NewLayout = new LayoutStruct(NexId());
            NewLayout.Profil_Name = "Copy of <- " + Source.Profil_Name + " ->";
            NewLayout.DeadZone = Source.DeadZone;

            foreach (LayoutBind SourceBind in Source._Bind)
            {
                NewLayout._Bind.Add(SourceBind);
            }

            /*   foreach(BaseLst SourceApp in Source._AppAuto)
               {
                  NewLayout._AppAuto.Add(new BaseLst(SourceApp.Txt, NewLayout.Profil_Id));
               }*/
            return _Layout.Add(NewLayout);

        }

        public short Default_Profil
        {
            get { return _Default_Profil; }
            set { _Default_Profil = value; }
        }

        public bool AutoSwitch
        {
            get { return _AutoSwitch; }
            set { _AutoSwitch = value; }
        }

        public bool InfoBulle
        {
            get { return _InfoBulle; }
            set { _InfoBulle = value; }
        }

        public bool StopIcon
        {
            get { return _StopIcon; }
            set { _StopIcon = value; }
        }

        public int DeviceId
        {
            get { return _DeviceId; }
            set { _DeviceId = value; }
        }

        public void LoadLayout()
        {

            LoadLayout(true);

        }

        public void LoadLayout(bool LoadBind)
        {

            string[] LayoutList;
            _Layout.Clear();

            Default_Profil = (short)myRegistry.ReadInt32("Default_Profil");
            if (Default_Profil == 0)
                Default_Profil = -1;

            AutoSwitch = (myRegistry.ReadInt32("AutoSwitch") != 0) ? true : false;

            InfoBulle = (myRegistry.ReadInt32("InfoBulle") != 0) ? true : false;

            StopIcon = (myRegistry.ReadInt32("StopIcon") != 0) ? true : false;

            DeviceId = myRegistry.ReadInt32("DeviceId");
            if (DeviceId == 0)
                DeviceId = 0xC626;

            LayoutList = myRegistry.SubKeyNames();
            if (LayoutList != null)
            {
                foreach (string LayoutName in LayoutList)
                {
                    if (LayoutName.IndexOf("Layout - ") == 0)
                    {
                        _Layout.Add(new LayoutStruct(LayoutName, LoadBind));
                    }
                }
            }

            if ((_Layout.Count == 0) && (LoadBind))
            {
                AddNewLayout();
            }
            _Layout.Sort();

        }

        public void Save()
        {

            myRegistry.DeleteSubKeyTree();
            myRegistry.Write("Default_Profil", (Int32)Default_Profil);
            myRegistry.Write("AutoSwitch", AutoSwitch ? 1 : 0);
            myRegistry.Write("InfoBulle", InfoBulle ? 1 : 0);
            myRegistry.Write("StopIcon", StopIcon ? 1 : 0);
            myRegistry.Write("DeviceId", DeviceId );
            foreach (LayoutStruct Layout in _Layout)
            {
                Layout.Save();
            }


        }

    }
}
﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Utilitaires;

namespace RBC9___HID
{
    static class Program
    {
        
        /// <summary>
        /// Point d'entrée principal de l'application.
        /// </summary>
        [STAThread]
        static void Main()
        {
  

            using (SingleInstanceApp app = new SingleInstanceApp("{RBC9 - HID - SpaceNavigator - Driver}"))
            {
                if (app.IsRunning())
                    MessageBox.Show("Application already running","RBC9 - SpaceNavigator");
                else
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);

                    RBC9NoForm applicationContext = new RBC9NoForm();
                    Application.Run(applicationContext);
                }

            }

          
        }
    }
}using System;
using System.Windows.Forms;
using System.Drawing;
using System.Diagnostics;
using System.Threading;
using System.Collections;
using USB_HID;
using Utilitaires;

namespace RBC9___HID
{


       public class RBC9NoForm : ApplicationContext
    {

        private System.ComponentModel.IContainer components;						// a list of components to dispose when the context is disposed
        private System.Windows.Forms.NotifyIcon MyNotifyIcon;				// the icon that sits in the system tray
        private System.Windows.Forms.ContextMenu MyNotifyIconContextMenu;	// the context menu for the notify icon

        private System.Windows.Forms.Form LayoutForm;						// the current form we're displaying
        private System.Windows.Forms.Form MxForm;

        private System.Windows.Forms.Timer IconTimer;
        private ArrayList MyIconList = new ArrayList();
        private int CurNumIcon=0;

        private SpaceNavigator SpaceNav;
        private MX1000 MyMx1000 = new MX1000();

        private short LastProfilNum = -999;
        private short DefaultProfilNum = -1;
        private ArrayList AppAutoList = new ArrayList();

        private Thread Thread_AutoSwitch;
        private bool Thread_AutoSwitch_Running;

        private bool InfoBulle;

        private int CurDevice;
           private string CurDevName;

        public RBC9NoForm()
        {
            InitializeContext();

            if (!Start_Nav())
            {
                this.MyNotifyIcon.BalloonTipIcon = ToolTipIcon.Warning;
                MyNotifyIcon.BalloonTipText = "! "+CurDevName+" not Found !";
                MyNotifyIcon.ShowBalloonTip(1500);
            }

            AutoSwitch_Start();
        }


        private void InitializeContext()
        {
            System.Windows.Forms.MenuItem NewMenuItem;

            this.components = new System.ComponentModel.Container();

            this.MyIconList.Add(new Icon(typeof(RBC9NoForm), "icon0.ico"));
            this.MyIconList.Add(new Icon(typeof(RBC9NoForm), "icon1.ico"));
            this.MyIconList.Add(new Icon(typeof(RBC9NoForm), "icon2.ico"));
            this.MyIconList.Add(new Icon(typeof(RBC9NoForm), "icon3.ico"));
            this.MyIconList.Add(new Icon(typeof(RBC9NoForm), "icon4.ico"));
            this.MyIconList.Add(new Icon(typeof(RBC9NoForm), "icon5.ico"));
            this.MyIconList.Add(new Icon(typeof(RBC9NoForm), "icon6.ico"));
            this.MyIconList.Add(new Icon(typeof(RBC9NoForm), "icon7.ico"));
            this.MyIconList.Add(new Icon(typeof(RBC9NoForm), "icon8.ico"));
            this.MyIconList.Add(new Icon(typeof(RBC9NoForm), "icon9.ico"));
            this.MyIconList.Add(new Icon(typeof(RBC9NoForm), "icon10.ico"));
            this.MyIconList.Add(new Icon(typeof(RBC9NoForm), "icon11.ico"));
            this.MyIconList.Add(new Icon(typeof(RBC9NoForm), "icon12.ico"));
            this.MyIconList.Add(new Icon(typeof(RBC9NoForm), "icon13.ico"));
            this.MyIconList.Add(new Icon(typeof(RBC9NoForm), "icon14.ico"));
            this.MyIconList.Add(new Icon(typeof(RBC9NoForm), "icon15.ico"));


            this.MyNotifyIcon = new System.Windows.Forms.NotifyIcon(this.components);
            this.MyNotifyIconContextMenu = new System.Windows.Forms.ContextMenu();

            // 
            // NotifyIcon
            // 
            this.MyNotifyIcon.ContextMenu = this.MyNotifyIconContextMenu;

            this.MyNotifyIcon.MouseDoubleClick += new MouseEventHandler(MyNotifyIcon_MouseDoubleClick);
            this.MyNotifyIcon.Icon = (Icon)MyIconList[0];

            this.MyNotifyIcon.Text = "RBC9 - SpaceDriver";
            this.MyNotifyIcon.BalloonTipTitle = this.MyNotifyIcon.Text;
            this.MyNotifyIcon.BalloonTipIcon = ToolTipIcon.Info;
            MyNotifyIcon.BalloonTipText = "! Wait For " + CurDevName+" ... !";

            this.MyNotifyIcon.Visible = true;

            // 
            // NotifyIconContextMenu
            // 

            MyNotifyIconContextMenu.MenuItems.Clear();

            if (MyMx1000.SetPointOk)
            {
                // 
                // AutoSwitch
                // 
                NewMenuItem = new MenuItem();
                NewMenuItem.Text = "MX1000 Auto";
                NewMenuItem.Name = "MXAutoSwitch";
                NewMenuItem.Click += new System.EventHandler(this.autoMxContextMenuItem_Click);
                NewMenuItem.Checked = MyMx1000.CurrentAuto;
                MyNotifyIconContextMenu.MenuItems.Add(NewMenuItem);
                // 
                // LayoutContextMenuItem
                // 
                NewMenuItem = new MenuItem();
                NewMenuItem.Text = "Edit Layout";
                NewMenuItem.Name = "MxForm";
                NewMenuItem.Click += new System.EventHandler(this.showContextMenuItem_Click);
                MyNotifyIconContextMenu.MenuItems.Add(NewMenuItem);

                NewMenuItem = new MenuItem();
                NewMenuItem.Text = "-";
                MyNotifyIconContextMenu.MenuItems.Add(NewMenuItem);

            }
            // 
            // AutoSwitch
            // 
            NewMenuItem = new MenuItem();
            NewMenuItem.Text = "Auto Switch";
            NewMenuItem.Name = "NavAutoSwitch";
            NewMenuItem.Click += new System.EventHandler(this.autoContextMenuItem_Click);
            MyNotifyIconContextMenu.MenuItems.Add(NewMenuItem);
            // 
            // LayoutContextMenuItem
            // 
            NewMenuItem = new MenuItem();
            NewMenuItem.Text = "Edit Layout";
            NewMenuItem.Name = "LayoutForm";
            NewMenuItem.Click += new System.EventHandler(this.showContextMenuItem_Click);
            MyNotifyIconContextMenu.MenuItems.Add(NewMenuItem);

            NewMenuItem = new MenuItem();
            NewMenuItem.Text = "-";
            MyNotifyIconContextMenu.MenuItems.Add(NewMenuItem);

            // 
            // exitContextMenuItem
            // 
            NewMenuItem = new MenuItem();
            NewMenuItem.Text = "&Exit";
            NewMenuItem.Name = "Exit";
            NewMenuItem.Click += new System.EventHandler(this.exitContextMenuItem_Click);
            MyNotifyIconContextMenu.MenuItems.Add(NewMenuItem);

            

            // 
            // IconTimer
            // 
            this.IconTimer = new System.Windows.Forms.Timer(this.components);
            this.IconTimer.Enabled = true;
            this.IconTimer.Interval = 100;
            this.IconTimer.Tick += new System.EventHandler(this.IconTimer_Tick);

            LoadLayout();

        }

        private bool Start_Nav()
        {
            SpaceNav = null;
            SpaceNav = SpaceNavigator.FindSpaceNav(CurDevice, 1);
            if (SpaceNav != null)
            {
                LastProfilNum = -999;
                SpaceNav.OnButtonChanged += new HIDChangedEventHandler(SpaceNav_OnButtonChanged);
                SpaceNav.OnDeviceRemoved += new HIDChangedEventHandler(SpaceNav_OnDeviceRemoved);
                SpaceNav.GetNavReport();
                return true;
            }
            
            return false;
        }
    
        private void AutoSwitch_Start()
        {
            AutoSwitch_Stop();
            Thread_AutoSwitch_Running = true;
            Thread_AutoSwitch = new Thread(new ThreadStart(AutoSwitch_CheckAppli));
            Thread_AutoSwitch.Start();

        }
        private void AutoSwitch_Stop()
        {
            Thread_AutoSwitch_Running = false;
            if (Thread_AutoSwitch != null)
            {
                Thread_AutoSwitch.Abort();
                while (Thread_AutoSwitch.IsAlive)
                {
                    Thread.Sleep(500);
                }
            }
            Thread_AutoSwitch = null;
        }
        private void AutoSwitch_CheckAppli()
        {
            string FocusApp;
            short NewProfilNum;

            DateTime Last_StartNav = DateTime.Now;

            while (Thread_AutoSwitch_Running)
            {

                Thread.Sleep(750); // ?? plus court ??

                if (SpaceNav == null)
                {
                    if (((TimeSpan)(DateTime.Now - Last_StartNav)).TotalMilliseconds > 5000)
                    {
                        Last_StartNav = DateTime.Now;
                        Start_Nav();
                    }
                }



                if ((SpaceNav != null)
                    && (MyNotifyIconContextMenu.MenuItems["NavAutoSwitch"].Checked))
                {
                    NewProfilNum = DefaultProfilNum;

                    FocusApp = User32.GetForegroundApp();
                    
                    if (FocusApp == null) continue;
                   // Debug.WriteLine(FocusApp);

                    foreach (BaseLst NewApp in AppAutoList)
                    {
                        if (NewApp.Txt.ToUpper().Equals(FocusApp))
                        {
                            NewProfilNum = (short)NewApp.Id;
                            break;
                        }
                    }

                    if (NewProfilNum != LastProfilNum)
                    {
                        Debug.WriteLine("Switch Profil");
                        SpaceNav.SelectProfil(NewProfilNum);
                    }
                }
            }

        }

        private void IconTimer_Tick(object sender, EventArgs e)
        {

            MyNotifyIcon.Icon = (Icon) MyIconList[CurNumIcon];

            CurNumIcon++;

            if (CurNumIcon >= MyIconList.Count)
                CurNumIcon = 0;

        }


           void MyNotifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            MyNotifyIcon.ShowBalloonTip(1000);

        }


        private void LoadLayout()
        {
            LayoutList SwitchLayout = new LayoutList();

            System.Windows.Forms.MenuItem NewMenuItem;
            System.Windows.Forms.MenuItem NewSubMenuItem;

            SwitchLayout.LoadLayout(false);
            AppAutoList.Clear();
            foreach (LayoutStruct MyLayout in SwitchLayout._Layout)
            {
                foreach (BaseLst NewAppList in MyLayout._AppAuto)
                {
                    AppAutoList.Add(NewAppList);
                }
            }
            DefaultProfilNum = SwitchLayout.Default_Profil;

            
            MyNotifyIconContextMenu.MenuItems.RemoveByKey("SwitchLayout");

            // 
            // SwitchContextMenuItem
            // 
            NewMenuItem = new MenuItem();
            NewMenuItem.Text = "Switch Layout";
            NewMenuItem.Name = "SwitchLayout";
            NewMenuItem.DefaultItem = true;
            MyNotifyIconContextMenu.MenuItems.Add(NewMenuItem);

            if (MyMx1000.SetPointOk)
            {
                NewMenuItem.Index = 5;
            }
            else
            {
                NewMenuItem.Index = 2;
            }

            foreach (LayoutStruct MyLayout in SwitchLayout._Layout)
            {
                NewSubMenuItem = new MenuItem();
                NewSubMenuItem.Text = MyLayout.Profil_Name;
                if (SwitchLayout.Default_Profil == MyLayout.Profil_Id)
                {
                    NewSubMenuItem.DefaultItem = true;
                }
                NewSubMenuItem.Tag = MyLayout.Profil_Id.ToString();
                NewSubMenuItem.Name = MyLayout.Profil_Id.ToString();
                NewSubMenuItem.Click += new System.EventHandler(this.SwitchMenuItem_Click);
                NewSubMenuItem.RadioCheck = true;

                NewMenuItem.MenuItems.Add(NewSubMenuItem);
            }

            MyNotifyIconContextMenu.MenuItems["NavAutoSwitch"].Checked = SwitchLayout.AutoSwitch;

            InfoBulle = SwitchLayout.InfoBulle;

            IconTimer.Enabled = !SwitchLayout.StopIcon;

            CurDevice = SwitchLayout.DeviceId;
            CurDevName = MyConst.MyTxt_ById(MyConst.MyDevice_Txt, CurDevice);
        }


        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
        }

        private void showContextMenuItem_Click(object sender, EventArgs e)
        {
            MenuItem MyMenu = (MenuItem)sender;

            ShowForm(MyMenu.Name.ToString());

        }

        private void autoContextMenuItem_Click(object sender, EventArgs e)
        {
            MenuItem MyMenu = (MenuItem)sender;

            MyMenu.Checked = !MyMenu.Checked;

        }

           private void autoMxContextMenuItem_Click(object sender, EventArgs e)
           {
               MenuItem MyMenu = (MenuItem)sender;

               MyMenu.Checked = !MyMenu.Checked;
               MyMx1000.CurrentAuto = MyMenu.Checked; 

           }

        private void SwitchMenuItem_Click(object sender, EventArgs e)
        {
            MenuItem MyMenu = (MenuItem)sender;
            if (MyNotifyIconContextMenu.MenuItems["NavAutoSwitch"].Checked)
            {
                if (MessageBox.Show(
               "AutoSwitch is on - Turn Off AutoSwitch ?",
               "AutoSwitch",
               MessageBoxButtons.YesNo)
               == DialogResult.Yes)
                {
                    MyNotifyIconContextMenu.MenuItems["NavAutoSwitch"].Checked = false;

                }
            }


            if (SpaceNav != null)
            {
                SpaceNav.SelectProfil(short.Parse(MyMenu.Tag.ToString()));
            }

        }

        private void exitContextMenuItem_Click(object sender, EventArgs e)
        {
            ExitThread();
        }

        private void ShowForm(string FormToShow)
        {

            switch (FormToShow)
            {
                case "LayoutForm":
                    
                    if (LayoutForm == null)
                    {
                        LayoutForm = new RBC9SpaceNav(ref SpaceNav);
                        LayoutForm.Show();
                        LayoutForm.Closed += new EventHandler(mainForm_Closed);
                    }
                    else
                    {
                        LayoutForm.Activate();
                    }

                    break;

                case "MxForm":

                    if (MxForm == null)
                    {
                        MyMx1000.CurrentAuto = false;
                        MxForm = new ParamMX1000(MyMx1000);
                        MxForm.Show();
                        MxForm.Closed += new EventHandler(mainForm_Closed);
                    }
                    else
                    {
                        MxForm.Activate();
                    }

                    break;
            }
        }


        private void mainForm_Closed(object sender, EventArgs e)
        {
            Form MyForm = (Form)sender;

            if (MyForm.Equals(this.LayoutForm))
            {
                this.LayoutForm = null;
                LastProfilNum = -999;
                LoadLayout();

                if (SpaceNav != null)
                {
                    if (SpaceNav.nPid != CurDevice)
                    {
                        if (!Start_Nav())
                        {
                            this.MyNotifyIcon.BalloonTipIcon = ToolTipIcon.Warning;
                            MyNotifyIcon.BalloonTipText = "! " + CurDevName + " not Found !";
                            MyNotifyIcon.ShowBalloonTip(1500);
                        }
                    }
                    if (SpaceNav != null)
                        SpaceNav.GetNavReport();
                }
            }

            if (MyForm.Equals(this.MxForm))
            {
                this.MxForm = null;
                MyMx1000.Load();
                MyNotifyIconContextMenu.MenuItems["MXAutoSwitch"].Checked = MyMx1000.CurrentAuto; ;

            }
        }

        protected override void ExitThreadCore()
        {
            AutoSwitch_Stop();

            if (LayoutForm != null) LayoutForm.Close();
            if (MxForm != null) MxForm.Close();
      

            if (SpaceNav != null)
            {
                SpaceNav.OnButtonChanged -= SpaceNav_OnButtonChanged;
                SpaceNav.OnDeviceRemoved -= SpaceNav_OnDeviceRemoved;
                SpaceNav = null;
            }

            if (MyMx1000 != null)
            {
                MyMx1000.AutoSwitch_Stop();
                MyMx1000 = null;
            }

            base.ExitThreadCore();
        }


        void SpaceNav_UpdateProfil(short ProfilNum)
        {
            if (ProfilNum != LastProfilNum)
            {
                this.MyNotifyIcon.BalloonTipIcon = ToolTipIcon.Info;
                MyNotifyIcon.BalloonTipText = "! Hardcoded Layout !";

                MenuItem MySwitch = MyNotifyIconContextMenu.MenuItems["SwitchLayout"];
                foreach (MenuItem OldLayout in MySwitch.MenuItems)
                {
                    OldLayout.Checked = false;
                }

                MenuItem MyLayout = MySwitch.MenuItems[ProfilNum.ToString()];
                if (MyLayout != null)
                {
                    MyNotifyIcon.BalloonTipText = "< " + MyLayout.Text.ToString() + " >";
                    MyLayout.Checked = true;
                }
                if (InfoBulle)
                {
                    MyNotifyIcon.ShowBalloonTip(2000);
                }
                LastProfilNum = ProfilNum;
            }



        }

        void SpaceNav_OnButtonChanged(object sender, HIDChangedEventArgs args)
        {
            

            if (args.HIDValue.IsRBC9Present)
            {
                SpaceNav_UpdateProfil(args.HIDValue.ProfilNum);
            }
            else
            {
                this.MyNotifyIcon.BalloonTipIcon = ToolTipIcon.Error;
                MyNotifyIcon.BalloonTipText = "! RBC9 Driver Not Installed !";
                MyNotifyIcon.ShowBalloonTip(2000);

            }

        }

        void SpaceNav_OnDeviceRemoved(object sender, HIDChangedEventArgs args)
        {
            Debug.WriteLine("Device Remove  ");
            SpaceNav = null;
            this.MyNotifyIcon.BalloonTipIcon = ToolTipIcon.Warning;
            MyNotifyIcon.BalloonTipText = "! Device Removed !";
            MyNotifyIcon.ShowBalloonTip(3000);
            Thread.Sleep(3000);
            this.MyNotifyIcon.BalloonTipIcon = ToolTipIcon.Info;
            MyNotifyIcon.BalloonTipText = "! Wait For "+CurDevName + " ... !";
            MyNotifyIcon.ShowBalloonTip(1000);
        
        }

    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using Utilitaires;
using USB_HID;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
using System.Collections;

using System.IO;

namespace RBC9___HID
{

     public partial class RBC9SpaceNav : Form
    {
         LayoutList MyLayout = new LayoutList();
         ArrayList MyBindFiltre = new ArrayList();
         SpaceNavigator myNav;
         SpaceNavigator MainNav;

         LayoutBind ClipBoardBind;
         BIND_FROM BindFrom=BIND_FROM.BIND_FROM_AXE;
         byte BindFromNum = 0;



         public RBC9SpaceNav(ref SpaceNavigator MainSpaceNav)
         {
             InitializeComponent();
             MainNav = MainSpaceNav;
         }

        private void RBC9_Load(object sender, EventArgs e)
        {
 
            Init_CboKey();

            MyLayout.LoadLayout();
            
            layoutStructBindingSource.DataSource = MyLayout._Layout;
            
            layoutAppAutoBindingSource.DataSource = ((LayoutStruct)layoutStructBindingSource.Current)._AppAuto;
            ProfilLstBindingSource.DataSource = MyLayout._Layout;
            DefaultLayoutBindingSource.DataSource = MyLayout._Layout;
            cboDefault.SelectedValue = MyLayout.Default_Profil;
            chkAutoApp.Checked = MyLayout.AutoSwitch;
            chkInfoBulle.Checked = MyLayout.InfoBulle;
            chkIcon.Checked = !MyLayout.StopIcon;

            cboDevice.SelectedValue = MyLayout.DeviceId;

            radioAxe_0.Checked = true;

            MyNavInit(MyLayout.DeviceId);

            if (MainNav != null)
            {
                MainNav.OnButtonChanged += new HIDChangedEventHandler(myNav_OnButtonChanged);
                MainNav.SetModeConfig(true);
                MainNav.GetNavReport();
            }

        }

         void MyNavInit(int nPid)
         {
             if (myNav != null)
             {
                 myNav.OnButtonChanged -= myNav_OnButtonChanged;

             }
             myNav = null;
             myNav = SpaceNavigator.FindSpaceNav(nPid,8);
             if (myNav != null)
             {
                 myNav.OnButtonChanged += new HIDChangedEventHandler(myNav_OnButtonChanged);
             }


             
             radioAxe_0.Checked = true;
             radio_Click(radioAxe_0, null);

             grpSpaceNav.Visible = (nPid == 0xc626) | (nPid == 0xc621);
             grpPilot.Visible = (nPid == 0xc625);
             grpTraveler.Visible = (nPid == 0xc623);
             
         }


         void Init_CboKey()
         {
           
             AxePartBindingSource.DataSource = MyConst.MyBindFrom_AxePart_Txt;
             PressTypeBindingSource.DataSource = MyConst.MyBindFrom_FromType_Txt;
             BindToBindingSource.DataSource = MyConst.MyBindTo_Txt;
             JoyAxeBindingSource.DataSource = MyConst.MyBindTo_JoyAxe_Txt;
             JoyBtnBindingSource.DataSource = MyConst.MyBindTo_JoyBtn_Txt;
             JoyPOVBindingSource.DataSource = MyConst.MyBindTo_JoyPov_Txt;
             MouBtnBindingSource.DataSource = MyConst.MyBindTo_MouBtn_Txt;
             WWWBindingSource.DataSource = MyConst.MyBindTo_KeyWWW_Txt;
             DeviceBindingSource.DataSource = MyConst.MyDevice_Txt;
            
             cboKey.DataSource = MyConst.MyBindTo_Key_Txt.Clone();
             cboKey.DisplayMember = "Txt";
             cboKey.ValueMember = "Id";

             cboKey1.DataSource = MyConst.MyBindTo_KeyCode_Txt.Clone();
             cboKey1.DisplayMember = "Txt";
             cboKey1.ValueMember = "Id";

             cboKey2.DataSource = MyConst.MyBindTo_KeyCode_Txt.Clone(); 
             cboKey2.DisplayMember = "Txt";
             cboKey2.ValueMember = "Id";

             cboKey3.DataSource = MyConst.MyBindTo_KeyCode_Txt.Clone();
             cboKey3.DisplayMember = "Txt";
             cboKey3.ValueMember = "Id";

             cboKey4.DataSource = MyConst.MyBindTo_KeyCode_Txt.Clone();
             cboKey4.DisplayMember = "Txt";
             cboKey4.ValueMember = "Id";

             cboKey5.DataSource = MyConst.MyBindTo_KeyCode_Txt.Clone();
             cboKey5.DisplayMember = "Txt";
             cboKey5.ValueMember = "Id";

         }

         void Synchro_LayoutLst()
         {
            
             DefaultLayoutBindingSource.ResetBindings(false);
             ProfilLstBindingSource.ResetBindings(false);

             Synchro_AppLst();

         }
         void Synchro_AppLst()
         {
             
             if (layoutStructBindingSource.Current != null)
             {
               
                 layoutAppAutoBindingSource.DataSource = ((LayoutStruct)layoutStructBindingSource.Current)._AppAuto;
             }
             else
             {
                 layoutAppAutoBindingSource.DataSource = null;
             }
     
             layoutAppAutoBindingSource.ResetBindings(true);
         }

         void ShowSpaceNavOption()
         {
             if (MyBindFiltre.Count > 0)
             {
                 switch (BindFrom)
                 {
                     case BIND_FROM.BIND_FROM_AXE:
                         grpSpaceNavAxe.Visible = true;
                         break;

                     case BIND_FROM.BIND_FROM_BTN:
                         grpSpaceNavAxe.Visible = false;
                         break;
                 }
                 grpSpaceNavBtn.Visible = !grpSpaceNavAxe.Visible;

             }
             else
             {
                 grpSpaceNavAxe.Visible = false;
                 grpSpaceNavBtn.Visible = false;

                 cbo_AllOnOff();
             }

         }

         void Load_Bind()
         {
             MyBindFiltre.Clear();

             if (layoutStructBindingSource.Current != null)
             {

                 foreach (LayoutBind Bind in ((LayoutStruct)layoutStructBindingSource.Current)._Bind)
                 {
                     if ((Bind.BindFrom == BindFrom) && (Bind.BindFromNum == BindFromNum))
                     {
                         MyBindFiltre.Add(Bind);

                     }
                 }

                 if (MyBindFiltre.Count > 0)
                 {
                     layoutBindBindingSource.DataSource = MyBindFiltre;
                 }

             }
             layoutBindBindingSource.ResetBindings(false);

             layoutBindBindingSource.Position = 0;

             ShowSpaceNavOption();

         }

        void myNav_OnButtonChanged(object sender, HIDChangedEventArgs args)
        {

            CheckForIllegalCrossThreadCalls = false;

            lbl_X.Text = args.HIDValue.Axe[0].State_Current.ToString();
            lbl_Y.Text = args.HIDValue.Axe[1].State_Current.ToString();
            lbl_Z.Text = args.HIDValue.Axe[2].State_Current.ToString();
            lbl_rY.Text = args.HIDValue.Axe[3].State_Current.ToString();
            lbl_rX.Text = args.HIDValue.Axe[4].State_Current.ToString();
            lbl_rZ.Text = args.HIDValue.Axe[5].State_Current.ToString();
            pictureLeft.Visible = args.HIDValue.Btn[0].State_Current;
            pictureRight.Visible = args.HIDValue.Btn[1].State_Current;


            radioBtn_0_Pil.ImageIndex = args.HIDValue.Btn[0].State_Current ? 1 : 0;
            radioBtn_1_Pil.ImageIndex = args.HIDValue.Btn[1].State_Current ? 1 : 0; ;
            radioBtn_2_Pil.ImageIndex = args.HIDValue.Btn[2].State_Current ? 1 : 0; ;
            radioBtn_3_Pil.ImageIndex = args.HIDValue.Btn[3].State_Current ? 1 : 0; ;
            radioBtn_4_Pil.ImageIndex = args.HIDValue.Btn[4].State_Current ? 1 : 0; ;
            radioBtn_5_Pil.ImageIndex = args.HIDValue.Btn[5].State_Current ? 1 : 0; ;
            radioBtn_6_Pil.ImageIndex = args.HIDValue.Btn[6].State_Current ? 1 : 0; ;
            radioBtn_7_Pil.ImageIndex = args.HIDValue.Btn[7].State_Current ? 1 : 0; ;
            radioBtn_8_Pil.ImageIndex = args.HIDValue.Btn[8].State_Current ? 1 : 0; ;
            radioBtn_9_Pil.ImageIndex = args.HIDValue.Btn[9].State_Current ? 1 : 0; ;
            radioBtn_10_Pil.ImageIndex = args.HIDValue.Btn[10].State_Current ? 1 : 0; ;
            radioBtn_11_Pil.ImageIndex = args.HIDValue.Btn[11].State_Current ? 1 : 0; ;
            radioBtn_12_Pil.ImageIndex = args.HIDValue.Btn[12].State_Current ? 1 : 0; ;
            radioBtn_13_Pil.ImageIndex = args.HIDValue.Btn[13].State_Current ? 1 : 0; ;
            radioBtn_14_Pil.ImageIndex = args.HIDValue.Btn[14].State_Current ? 1 : 0; ;
            radioBtn_15_Pil.ImageIndex = args.HIDValue.Btn[15].State_Current ? 1 : 0; ;
            radioBtn_16_Pil.ImageIndex = args.HIDValue.Btn[16].State_Current ? 1 : 0; ;
            radioBtn_17_Pil.ImageIndex = args.HIDValue.Btn[17].State_Current ? 1 : 0; ;
            radioBtn_18_Pil.ImageIndex = args.HIDValue.Btn[18].State_Current ? 1 : 0; ;
            radioBtn_19_Pil.ImageIndex = args.HIDValue.Btn[19].State_Current ? 1 : 0; ;
            radioBtn_20_Pil.ImageIndex = args.HIDValue.Btn[20].State_Current ? 1 : 0; ;


            radioBtn_0_Trav.ImageIndex = args.HIDValue.Btn[0].State_Current ? 1 : 0; ;
            radioBtn_1_Trav.ImageIndex = args.HIDValue.Btn[1].State_Current ? 1 : 0; ;
            radioBtn_2_Trav.ImageIndex = args.HIDValue.Btn[2].State_Current ? 1 : 0; ;
            radioBtn_3_Trav.ImageIndex = args.HIDValue.Btn[3].State_Current ? 1 : 0; ;
            radioBtn_4_Trav.ImageIndex = args.HIDValue.Btn[4].State_Current ? 1 : 0; ;
            radioBtn_5_Trav.ImageIndex = args.HIDValue.Btn[5].State_Current ? 1 : 0; ;
            radioBtn_6_Trav.ImageIndex = args.HIDValue.Btn[6].State_Current ? 1 : 0; ;
            radioBtn_7_Trav.ImageIndex = args.HIDValue.Btn[7].State_Current ? 1 : 0; ;

            
        }
  
            
         private void trkDeadZone_Scroll_1(object sender, EventArgs e)
         {
             txtDeadZone.Text = ((TrackBar)sender).Value.ToString();

             if (layoutBindBindingSource.Current != null)
             {
                 if (((LayoutBind)layoutBindBindingSource.Current).BindFrom == BIND_FROM.BIND_FROM_AXE)
                 {
                     lblAxeDead.Text = Convert.ToString(((TrackBar)sender).Value + ((LayoutBind)layoutBindBindingSource.Current).DeadZone);
                 }
             }

         }
     
         private void layoutStructBindingSource_PositionChanged(object sender, EventArgs e)
         {
             Load_Bind();
             Synchro_AppLst();
            
         }


         private void Add_Bind()
         {
             if (layoutStructBindingSource.Current == null) return;

             LayoutBind NewBind = new LayoutBind(BindFrom, BindFromNum);

             ((LayoutStruct)layoutStructBindingSource.Current)._Bind.Add(NewBind);

             Load_Bind();

             layoutBindBindingSource.Position = layoutBindBindingSource.IndexOf(NewBind);
         }
     
         private void Del_Bind()
         {
             if (layoutBindBindingSource.Current != null)
             {


                 if (MessageBox.Show(
                  "<" + ((LayoutBind)layoutBindBindingSource.Current).BindTo_Txt + " - " +((LayoutBind)layoutBindBindingSource.Current).Comment + "> ?",
                  "Delete Bind",
                  MessageBoxButtons.YesNo)
                  == DialogResult.Yes)
                 {

                     ((LayoutStruct)layoutStructBindingSource.Current)._Bind.Remove(layoutBindBindingSource.Current);
                     layoutBindBindingSource.RemoveCurrent();

                     ShowSpaceNavOption();

                 }
             }
         }
         
         private void RBC9SpaceNav_FormClosed(object sender, FormClosedEventArgs e)
         {
           
             if (myNav != null)
             {
                myNav.OnButtonChanged -= myNav_OnButtonChanged;
      
             }

             if (MainNav != null)
             {
                 MainNav.OnButtonChanged -= myNav_OnButtonChanged;
                 MainNav.SetModeConfig(false);
                 MainNav.ReloadProfil();
             }
         }


         private void trkMinVal_Scroll_1(object sender, EventArgs e)
         {
             TrackBar NewTrack = (TrackBar)sender;
             if (NewTrack.Value > trkMaxVal.Value)
                 NewTrack.Value = trkMaxVal.Value;

             lblMin.Text = NewTrack.Value.ToString();

         }

         private void trkMaxVal_Scroll_1(object sender, EventArgs e)
         {
             TrackBar NewTrack = (TrackBar)sender;
             if (NewTrack.Value < trkMinVal.Value)
                 NewTrack.Value = trkMinVal.Value;

             lblMax.Text = NewTrack.Value.ToString();
         }

         private void cbo_AllOnOff()
         {
             cbo_AllOnOff(false);
         }
         private void cbo_AllOnOff(bool Visible)
         {

             grpBindType.Visible = Visible;
             grpJoyAxe.Visible = Visible;
             grpJoyBtn.Visible = Visible;
             grpJoyPov.Visible = Visible;
             grpMouBtn.Visible = Visible;
             grpMouseSensi.Visible = Visible;
             grpLayout.Visible = Visible;
             grpKey.Visible = Visible;
             grpWWW.Visible = Visible;
             grpTypePress.Visible = Visible;
             grpTypeDelay.Visible = Visible;
             grpComment.Visible = Visible;
         }

         private void Show_Cbo()
         {
             BIND_TO MyBindTo;
        
             if (cboBintTo.SelectedItem == null) return;

             grpBindType.Visible = true;
             grpTypePress.Visible = true;
             grpComment.Visible = true;

             MyBindTo = (BIND_TO)((BaseLst)cboBintTo.SelectedItem).Id;
       
             grpJoyAxe.Visible = (MyBindTo == BIND_TO.BIND_TO_JOYSTICK_AXE);
             grpJoyBtn.Visible = (MyBindTo == BIND_TO.BIND_TO_JOYSTICK_BTN);
             grpJoyPov.Visible = (MyBindTo == BIND_TO.BIND_TO_JOYSTICK_POV);

             grpMouBtn.Visible = (MyBindTo == BIND_TO.BIND_TO_MOUSE_BTN);

             grpMouseSensi.Visible = ((MyBindTo == BIND_TO.BIND_TO_MOUSE_X)
                 || (MyBindTo == BIND_TO.BIND_TO_MOUSE_Y)
             || (MyBindTo == BIND_TO.BIND_TO_MOUSE_WHEEL));

             switch (MyBindTo)
             {
                 case BIND_TO.BIND_TO_MOUSE_X:
                     lblMouSensi.Text = "Sensitivity :";
                     lblMouSensiTaux.Text = "%";
                     break;

                 case BIND_TO.BIND_TO_MOUSE_Y:
                     lblMouSensi.Text = "Sensitivity :";
                     lblMouSensiTaux.Text = "%";
                     break;

                 case BIND_TO.BIND_TO_MOUSE_WHEEL:
                     lblMouSensi.Text = "Delay :";
                     lblMouSensiTaux.Text = " / 100 sec.";
                     break;

             }

             grpLayout.Visible = (MyBindTo == BIND_TO.BIND_TO_PROFIL);
          
             grpKey.Visible = (MyBindTo == BIND_TO.BIND_TO_KEYB);

             grpWWW.Visible = (MyBindTo == BIND_TO.BIND_TO_WWW);

             if (layoutStructBindingSource.Current != null)
             {
                 if (layoutBindBindingSource.Current != null)
                 {
                     if (((LayoutBind)layoutBindBindingSource.Current).BindFrom == BIND_FROM.BIND_FROM_AXE)
                     {
                         lblAxeDead.Text = Convert.ToString(((LayoutStruct)layoutStructBindingSource.Current).DeadZone + ((LayoutBind)layoutBindBindingSource.Current).DeadZone);
                     }
                 }
             }
             else
             {
                 lblAxeDead.Text = "";
             }

             if (cboPressType.SelectedValue != null)
             {
                 grpTypeDelay.Visible = ((PRESS_TYPE)cboPressType.SelectedValue != PRESS_TYPE.PRESS_STD);
             }
             else
             {
                 grpTypeDelay.Visible = false;
             }
             
         }

         private void cboBintTo_SelectionChangeCommitted(object sender, EventArgs e)
         {
             if (layoutBindBindingSource.Current != null)
             {

                 ((LayoutBind)layoutBindBindingSource.Current).BindTo = (BIND_TO)((BaseLst)cboBintTo.SelectedItem).Id;
                 layoutBindBindingSource.ResetCurrentItem();

             }
              
             Show_Cbo();
         }

         private void trkMouSensi_Scroll(object sender, EventArgs e)
         {
             TrackBar MyScroll = (TrackBar)sender;
             if (MyScroll.Value < 1)
             {
                 MyScroll.Value = 1;
             }
             ((LayoutBind)layoutBindBindingSource.Current).BindTo_MouSensi = (byte) MyScroll.Value;
             layoutBindBindingSource.ResetCurrentItem();
            
         }

     
        
         private void trkRepeat_Scroll(object sender, EventArgs e)
         {
             TrackBar MyScroll = (TrackBar)sender;
             if (MyScroll.Value < 10)
             {
                 MyScroll.Value = 10;
             }
             ((LayoutBind)layoutBindBindingSource.Current).BindTo_KeyDelay = (short)MyScroll.Value;
             layoutBindBindingSource.ResetCurrentItem();
         }

         private void gridLayout_CellValueChanged(object sender, DataGridViewCellEventArgs e)
         {
             Synchro_LayoutLst();
         }

         private void cboDefault_SelectedIndexChanged(object sender, EventArgs e)
         {
             ComboBox MyDefault = (ComboBox) sender;
             
             if (MyDefault.SelectedItem == null) return;

             MyLayout.Default_Profil = (short) MyDefault.SelectedValue;
         }

          
         private void radio_Click(object sender, EventArgs e)
         {
             if (sender == null) return;

             radioBtn_Nul_Nav.Checked = true;
             radioBtn_Nul_Pil.Checked = true;
             radioBtn_Nul_Axe.Checked = true;
             radioBtn_Nul_Trav.Checked = true;
             
             RadioButton MyRadio = (RadioButton)sender;
             
             MyRadio.Checked = true;

             switch (MyRadio.Tag.ToString().Substring(0, 3))
             {
                 case "Axe":
                     BindFrom = BIND_FROM.BIND_FROM_AXE;
                     break;

                 case "Btn":
                     BindFrom = BIND_FROM.BIND_FROM_BTN;
                     break;
             }

             BindFromNum = Convert.ToByte(MyRadio.Tag.ToString().Substring(4));

             Load_Bind();
         }


         private void btnApply_Click(object sender, EventArgs e)
         {

             if (MessageBox.Show(
                "Apply New Layout ?",
                "RBC9 - SpaceNavigator",
                MessageBoxButtons.YesNo)
                == DialogResult.Yes)
             {
                 MyLayout.Save();
                 this.Close();

             }
          }

         private void btnCancel_Click(object sender, EventArgs e)
         {
             if (MessageBox.Show(
                "Quit without Save ?",
                "RBC9 - SpaceNavigator",
                MessageBoxButtons.YesNo)
                == DialogResult.Yes)
             {
                 this.Close();
             }

         }

         private void btnDelAppAuto_Click(object sender, EventArgs e)
         {
            
             if ( layoutAppAutoBindingSource.Current != null)
             {
                 if (MessageBox.Show(
                 "<" + ((BaseLst)layoutAppAutoBindingSource.Current).Txt + "> ?",
                 "Delete App",
                 MessageBoxButtons.YesNo)
                 == DialogResult.Yes)
                 {
                     layoutAppAutoBindingSource.RemoveCurrent();
                     
                 }
             }
         }

         private void btnAddAppAuto_Click(object sender, EventArgs e)
         {

             if (layoutStructBindingSource.Current == null) return;


             BaseLst NewApp = new BaseLst("< New App >", ((LayoutStruct)layoutStructBindingSource.Current).Profil_Id);

             ((LayoutStruct)layoutStructBindingSource.Current)._AppAuto.Add(NewApp);


             layoutAppAutoBindingSource.ResetBindings(true);
             layoutAppAutoBindingSource.Position = layoutAppAutoBindingSource.IndexOf(NewApp);
             
         }

         private void chkAutoApp_CheckedChanged(object sender, EventArgs e)
         {
             CheckBox MyAuto = (CheckBox)sender;

             if (MyAuto == null) return;

             MyLayout.AutoSwitch = MyAuto.Checked;
         }

         private void gridBindTo_SelectionChanged(object sender, EventArgs e)
         {
             Show_Cbo();
         }

         private void btnCalib_Click(object sender, EventArgs e)
         {

             if (MessageBox.Show(
                "Calibrer ?",
                "RBC9 - SpaceNavigator",
                MessageBoxButtons.YesNo)
                == DialogResult.Yes)
             {
                 if (MainNav != null) MainNav.Calibrate();
                
             }
         }

         private void trkAxeZone_Scroll(object sender, EventArgs e)
         {
             TrackBar NewTrack = (TrackBar)sender;
             if (NewTrack.Value > trkAxeZone.Value)
                 NewTrack.Value = trkAxeZone.Value;

             lblAxeDead.Text = Convert.ToString(((LayoutStruct)layoutStructBindingSource.Current).DeadZone + NewTrack.Value);

         }

         private void gridBindTo_MouseClick(object sender, MouseEventArgs e)
         {
             if (e.Button == MouseButtons.Right)
             {
                 int CurrentRow = gridBindTo.HitTest(e.X, e.Y).RowIndex;
                 if (CurrentRow >= 0)
                 {
                     layoutBindBindingSource.Position = CurrentRow;

                     MenuBindCopy.Enabled = true;
                     MenuBindDel.Enabled = true;
                 }
                 else
                 {
                     MenuBindCopy.Enabled = false;
                     MenuBindDel.Enabled = false;
                 }

                 MenuBindPaste.Enabled = false;

                 if (layoutStructBindingSource.Current != null)
                 {
                     if (ClipBoardBind != null)
                     {
                             MenuBindPaste.Enabled = true;
                    }
                 }

                 MenuBind.Show(gridBindTo, e.Location);
             }
         }

         private void MenuBindDel_Click(object sender, EventArgs e)
         {
             Del_Bind();
         }

         private void MenuBindAdd_Click(object sender, EventArgs e)
         {
             Add_Bind();
         }

         private void MenuBindCopy_Click(object sender, EventArgs e)
         {

             if (layoutBindBindingSource.Current != null)
             {


                     ClipBoardBind = (LayoutBind)layoutBindBindingSource.Current;
                   

             }
         }

         private void MenuBindPaste_Click(object sender, EventArgs e)
         {
             if (MessageBox.Show(
                       "<" + ClipBoardBind.BindTo_Txt + " - " + ClipBoardBind .Comment + "> ?",
                       "Paste Bind",
                       MessageBoxButtons.YesNo)
                       == DialogResult.Yes)
             {

                 LayoutBind NewBind = new LayoutBind(ClipBoardBind.BindByte);
                 
                 if (NewBind.BindFrom != BindFrom) NewBind.BindFrom = BindFrom;
                 NewBind.BindFromNum = BindFromNum;
                 ((LayoutStruct)layoutStructBindingSource.Current)._Bind.Add(NewBind);

                 Load_Bind();

                 layoutBindBindingSource.Position = layoutBindBindingSource.IndexOf(NewBind);

             }
         }

         private void MenuLayoutAdd_Click(object sender, EventArgs e)
         {
             int NewPos = MyLayout.AddNewLayout();
             layoutStructBindingSource.ResetBindings(false);
             layoutStructBindingSource.Position = NewPos;
             Synchro_LayoutLst();
         }

         private void MenuLayoutDel_Click(object sender, EventArgs e)
         {
             if (layoutStructBindingSource.Current != null)
             {
                 if (MessageBox.Show(
                 "<" + ((LayoutStruct)layoutStructBindingSource.Current).Profil_Name + "> ?",
                 "Delete Layout",
                 MessageBoxButtons.YesNo)
                 == DialogResult.Yes)
                 {
                     layoutStructBindingSource.RemoveCurrent();
                     Synchro_LayoutLst();
                 }
             }
         }


         private void gridLayout_MouseClick(object sender, MouseEventArgs e)
         {
             if (e.Button == MouseButtons.Right)
             {
                 int CurrentRow = gridLayout.HitTest(e.X, e.Y).RowIndex;
                 if (CurrentRow >= 0)
                 {
                     layoutStructBindingSource.Position = CurrentRow;


                     MenuLayoutImport.Enabled = true;
                     MenuLayoutExport.Enabled = true;
                     MenuLayoutDuplicate.Enabled = true;
                     MenuLayoutDel.Enabled = true;
                 }
                 else
                 {
                     MenuLayoutImport.Enabled = false;
                     MenuLayoutExport.Enabled = false;
                     MenuLayoutDuplicate.Enabled = false;
                     MenuLayoutDel.Enabled = false;
                 }

                 MenuLayout.Show(gridLayout, e.Location);
             }
         }

         private void MenuLayoutDuplicate_Click(object sender, EventArgs e)
         {
             if (MessageBox.Show(
                "<" + ((LayoutStruct)layoutStructBindingSource.Current).Profil_Name + "> ?",
                "Duplicate Layout",
                MessageBoxButtons.YesNo)
                == DialogResult.Yes)
             {
                 int NewPos = MyLayout.Duplicate((LayoutStruct)layoutStructBindingSource.Current);
                 layoutStructBindingSource.ResetBindings(false);
                 layoutStructBindingSource.Position = NewPos;
                 Synchro_LayoutLst();
             }
             
         }

         private void MenuLayoutExport_Click(object sender, EventArgs e)
         {
                saveFileBind.FileName = ((LayoutStruct)layoutStructBindingSource.Current).Profil_Name;
                 if (saveFileBind.ShowDialog() == DialogResult.OK)
                 {
                     ((LayoutStruct)layoutStructBindingSource.Current).ExportBind(saveFileBind.FileName);
                 }
            

         }

         private void MenuLayoutImport_Click(object sender, EventArgs e)
         {
             openFileBind.FileName = "";
             if (openFileBind.ShowDialog() == DialogResult.OK)
             {
                 ((LayoutStruct)layoutStructBindingSource.Current).ImportBind(openFileBind.FileName);
             }
         }

         private void chkInfoBulle_CheckedChanged(object sender, EventArgs e)
         {
             CheckBox MyAuto = (CheckBox)sender;

             if (MyAuto == null) return;

             MyLayout.InfoBulle = MyAuto.Checked;
         }

         private void chkIcon_CheckedChanged(object sender, EventArgs e)
         {
             CheckBox MyAuto = (CheckBox)sender;

             if (MyAuto == null) return;

             MyLayout.StopIcon = !MyAuto.Checked;
         }

         private void trkBtnDelay_Scroll(object sender, EventArgs e)
         {
           
             lblTypeDelay.Text = ((TrackBar)sender).Value.ToString();
            
         }

    

         private void BtnTypeBindingSource_CurrentChanged(object sender, EventArgs e)
         {
             grpTypeDelay.Visible = ((PRESS_TYPE)((BaseLst)PressTypeBindingSource.Current).Id != PRESS_TYPE.PRESS_STD);
         }

       

         private void cboBtnType_SelectionChangeCommitted(object sender, EventArgs e)
         {
             if (layoutBindBindingSource.Current != null)
             {

                 ((LayoutBind)layoutBindBindingSource.Current).FromType = (PRESS_TYPE)((BaseLst)cboPressType.SelectedItem).Id;
                 layoutBindBindingSource.ResetCurrentItem();

             }
         }

  

         private void cboDevice_SelectedIndexChanged(object sender, EventArgs e)
         {

             ComboBox MyDevice = (ComboBox)sender;

             if (MyDevice.SelectedItem == null) return;

             MyLayout.DeviceId = (int)MyDevice.SelectedValue;

             MyNavInit(MyLayout.DeviceId);
         }
 
                       
                      
    }
}﻿namespace RBC9___HID
{
    partial class RBC9SpaceNav
    {
        /// <summary>
        /// Variable nécessaire au concepteur.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Nettoyage des ressources utilisées.
        /// </summary>
        /// <param name="disposing">true si les ressources managées doivent être supprimées ; sinon, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Code généré par le Concepteur Windows Form

        /// <summary>
        /// Méthode requise pour la prise en charge du concepteur - ne modifiez pas
        /// le contenu de cette méthode avec l'éditeur de code.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RBC9SpaceNav));
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle4 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle5 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle6 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle7 = new System.Windows.Forms.DataGridViewCellStyle();
            this.pictureRight = new System.Windows.Forms.PictureBox();
            this.pictureLeft = new System.Windows.Forms.PictureBox();
            this.lbl_rZ = new System.Windows.Forms.Label();
            this.lbl_rY = new System.Windows.Forms.Label();
            this.lbl_rX = new System.Windows.Forms.Label();
            this.lbl_Z = new System.Windows.Forms.Label();
            this.lbl_Y = new System.Windows.Forms.Label();
            this.lbl_X = new System.Windows.Forms.Label();
            this.gridLayout = new System.Windows.Forms.DataGridView();
            this.profilNameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.layoutStructBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.grpDeadZone = new System.Windows.Forms.GroupBox();
            this.trkDeadZone = new System.Windows.Forms.TrackBar();
            this.txtDeadZone = new System.Windows.Forms.TextBox();
            this.grpSpaceNavAxe = new System.Windows.Forms.GroupBox();
            this.lblAxeDead = new System.Windows.Forms.Label();
            this.lblMin = new System.Windows.Forms.Label();
            this.layoutBindBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.label4 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.trkAxeZone = new System.Windows.Forms.TrackBar();
            this.label1 = new System.Windows.Forms.Label();
            this.lblMax = new System.Windows.Forms.Label();
            this.trkMaxVal = new System.Windows.Forms.TrackBar();
            this.trkMinVal = new System.Windows.Forms.TrackBar();
            this.cboAxePart = new System.Windows.Forms.ComboBox();
            this.AxePartBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.chkInvert = new System.Windows.Forms.CheckBox();
            this.cboKey5 = new System.Windows.Forms.ComboBox();
            this.grpSpaceNavBtn = new System.Windows.Forms.GroupBox();
            this.chkInvertBtn = new System.Windows.Forms.CheckBox();
            this.grpTypeDelay = new System.Windows.Forms.GroupBox();
            this.lblTypeDelay = new System.Windows.Forms.Label();
            this.trkTypeDelay = new System.Windows.Forms.TrackBar();
            this.cboPressType = new System.Windows.Forms.ComboBox();
            this.PressTypeBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.cboBintTo = new System.Windows.Forms.ComboBox();
            this.BindToBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.cboJoyAxe = new System.Windows.Forms.ComboBox();
            this.JoyAxeBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.cboJoyPOV = new System.Windows.Forms.ComboBox();
            this.JoyPOVBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.cboJoyBtn = new System.Windows.Forms.ComboBox();
            this.JoyBtnBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.cboMouBtn = new System.Windows.Forms.ComboBox();
            this.MouBtnBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.trkMouSensi = new System.Windows.Forms.TrackBar();
            this.lblValSensi = new System.Windows.Forms.Label();
            this.lblMouSensi = new System.Windows.Forms.Label();
            this.lblMouSensiTaux = new System.Windows.Forms.Label();
            this.cboKey1 = new System.Windows.Forms.ComboBox();
            this.cboKey2 = new System.Windows.Forms.ComboBox();
            this.cboKey3 = new System.Windows.Forms.ComboBox();
            this.cboKey4 = new System.Windows.Forms.ComboBox();
            this.cboKey = new System.Windows.Forms.ComboBox();
            this.chkRepeat = new System.Windows.Forms.CheckBox();
            this.trkRepeat = new System.Windows.Forms.TrackBar();
            this.lblRepeatDelay = new System.Windows.Forms.Label();
            this.grpLayout = new System.Windows.Forms.GroupBox();
            this.cboProfil = new System.Windows.Forms.ComboBox();
            this.ProfilLstBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.grpMouBtn = new System.Windows.Forms.GroupBox();
            this.grpJoyBtn = new System.Windows.Forms.GroupBox();
            this.grpJoyPov = new System.Windows.Forms.GroupBox();
            this.grpJoyAxe = new System.Windows.Forms.GroupBox();
            this.grpMouseSensi = new System.Windows.Forms.GroupBox();
            this.grpKey = new System.Windows.Forms.GroupBox();
            this.grpWWW = new System.Windows.Forms.GroupBox();
            this.cboWWW = new System.Windows.Forms.ComboBox();
            this.WWWBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.grpBindType = new System.Windows.Forms.GroupBox();
            this.cboDefault = new System.Windows.Forms.ComboBox();
            this.DefaultLayoutBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.grpDefault = new System.Windows.Forms.GroupBox();
            this.pictureSpaceNav = new System.Windows.Forms.PictureBox();
            this.radioAxe_1 = new System.Windows.Forms.RadioButton();
            this.radioAxe_0 = new System.Windows.Forms.RadioButton();
            this.radioAxe_2 = new System.Windows.Forms.RadioButton();
            this.radioAxe_4 = new System.Windows.Forms.RadioButton();
            this.radioAxe_3 = new System.Windows.Forms.RadioButton();
            this.radioAxe_5 = new System.Windows.Forms.RadioButton();
            this.radioBtn_1_Nav = new System.Windows.Forms.RadioButton();
            this.radioBtn_0_Nav = new System.Windows.Forms.RadioButton();
            this.btnApply = new System.Windows.Forms.Button();
            this.btnCancel = new System.Windows.Forms.Button();
            this.gridAppAuto = new System.Windows.Forms.DataGridView();
            this.txtDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.layoutAppAutoBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.tabControl1 = new System.Windows.Forms.TabControl();
            this.tabPage1 = new System.Windows.Forms.TabPage();
            this.grpComment = new System.Windows.Forms.GroupBox();
            this.txtComment = new System.Windows.Forms.TextBox();
            this.grpTypePress = new System.Windows.Forms.GroupBox();
            this.gridBindTo = new System.Windows.Forms.DataGridView();
            this.bindToTxtDataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.Comment = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.tabPage2 = new System.Windows.Forms.TabPage();
            this.btnDelAppAuto = new System.Windows.Forms.Button();
            this.btnAddAppAuto = new System.Windows.Forms.Button();
            this.chkAutoApp = new System.Windows.Forms.CheckBox();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.cboDevice = new System.Windows.Forms.ComboBox();
            this.DeviceBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.chkIcon = new System.Windows.Forms.CheckBox();
            this.chkInfoBulle = new System.Windows.Forms.CheckBox();
            this.btnCalib = new System.Windows.Forms.Button();
            this.MenuBind = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.MenuBindAdd = new System.Windows.Forms.ToolStripMenuItem();
            this.MenuBindDel = new System.Windows.Forms.ToolStripMenuItem();
            this.MenuBindSeparator = new System.Windows.Forms.ToolStripSeparator();
            this.MenuBindCopy = new System.Windows.Forms.ToolStripMenuItem();
            this.MenuBindPaste = new System.Windows.Forms.ToolStripMenuItem();
            this.MenuLayout = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.MenuLayoutAdd = new System.Windows.Forms.ToolStripMenuItem();
            this.MenuLayoutDel = new System.Windows.Forms.ToolStripMenuItem();
            this.MenuLayoutSeparator = new System.Windows.Forms.ToolStripSeparator();
            this.MenuLayoutDuplicate = new System.Windows.Forms.ToolStripMenuItem();
            this.MenuLayoutExport = new System.Windows.Forms.ToolStripMenuItem();
            this.MenuLayoutImport = new System.Windows.Forms.ToolStripMenuItem();
            this.openFileBind = new System.Windows.Forms.OpenFileDialog();
            this.saveFileBind = new System.Windows.Forms.SaveFileDialog();
            this.grpSpaceNav = new System.Windows.Forms.GroupBox();
            this.radioBtn_Nul_Nav = new System.Windows.Forms.RadioButton();
            this.grpPilot = new System.Windows.Forms.GroupBox();
            this.radioBtn_20_Pil = new System.Windows.Forms.RadioButton();
            this.PilotImageList = new System.Windows.Forms.ImageList(this.components);
            this.radioBtn_19_Pil = new System.Windows.Forms.RadioButton();
            this.radioBtn_18_Pil = new System.Windows.Forms.RadioButton();
            this.radioBtn_17_Pil = new System.Windows.Forms.RadioButton();
            this.radioBtn_16_Pil = new System.Windows.Forms.RadioButton();
            this.radioBtn_15_Pil = new System.Windows.Forms.RadioButton();
            this.radioBtn_14_Pil = new System.Windows.Forms.RadioButton();
            this.radioBtn_13_Pil = new System.Windows.Forms.RadioButton();
            this.radioBtn_12_Pil = new System.Windows.Forms.RadioButton();
            this.radioBtn_11_Pil = new System.Windows.Forms.RadioButton();
            this.radioBtn_10_Pil = new System.Windows.Forms.RadioButton();
            this.radioBtn_9_Pil = new System.Windows.Forms.RadioButton();
            this.radioBtn_8_Pil = new System.Windows.Forms.RadioButton();
            this.radioBtn_7_Pil = new System.Windows.Forms.RadioButton();
            this.radioBtn_6_Pil = new System.Windows.Forms.RadioButton();
            this.radioBtn_5_Pil = new System.Windows.Forms.RadioButton();
            this.radioBtn_4_Pil = new System.Windows.Forms.RadioButton();
            this.radioBtn_3_Pil = new System.Windows.Forms.RadioButton();
            this.radioBtn_2_Pil = new System.Windows.Forms.RadioButton();
            this.radioBtn_1_Pil = new System.Windows.Forms.RadioButton();
            this.radioBtn_Nul_Pil = new System.Windows.Forms.RadioButton();
            this.radioBtn_0_Pil = new System.Windows.Forms.RadioButton();
            this.picturePilot = new System.Windows.Forms.PictureBox();
            this.radioBtn_Nul_Axe = new System.Windows.Forms.RadioButton();
            this.grpTraveler = new System.Windows.Forms.GroupBox();
            this.radioBtn_7_Trav = new System.Windows.Forms.RadioButton();
            this.radioBtn_6_Trav = new System.Windows.Forms.RadioButton();
            this.radioBtn_5_Trav = new System.Windows.Forms.RadioButton();
            this.radioBtn_4_Trav = new System.Windows.Forms.RadioButton();
            this.radioBtn_3_Trav = new System.Windows.Forms.RadioButton();
            this.radioBtn_2_Trav = new System.Windows.Forms.RadioButton();
            this.radioBtn_1_Trav = new System.Windows.Forms.RadioButton();
            this.radioBtn_Nul_Trav = new System.Windows.Forms.RadioButton();
            this.radioBtn_0_Trav = new System.Windows.Forms.RadioButton();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            ((System.ComponentModel.ISupportInitialize)(this.pictureRight)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureLeft)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.gridLayout)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.layoutStructBindingSource)).BeginInit();
            this.grpDeadZone.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.trkDeadZone)).BeginInit();
            this.grpSpaceNavAxe.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.layoutBindBindingSource)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.trkAxeZone)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.trkMaxVal)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.trkMinVal)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.AxePartBindingSource)).BeginInit();
            this.grpSpaceNavBtn.SuspendLayout();
            this.grpTypeDelay.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.trkTypeDelay)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.PressTypeBindingSource)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.BindToBindingSource)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.JoyAxeBindingSource)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.JoyPOVBindingSource)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.JoyBtnBindingSource)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.MouBtnBindingSource)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.trkMouSensi)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.trkRepeat)).BeginInit();
            this.grpLayout.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.ProfilLstBindingSource)).BeginInit();
            this.grpMouBtn.SuspendLayout();
            this.grpJoyBtn.SuspendLayout();
            this.grpJoyPov.SuspendLayout();
            this.grpJoyAxe.SuspendLayout();
            this.grpMouseSensi.SuspendLayout();
            this.grpKey.SuspendLayout();
            this.grpWWW.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.WWWBindingSource)).BeginInit();
            this.grpBindType.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.DefaultLayoutBindingSource)).BeginInit();
            this.grpDefault.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.pictureSpaceNav)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.gridAppAuto)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.layoutAppAutoBindingSource)).BeginInit();
            this.tabControl1.SuspendLayout();
            this.tabPage1.SuspendLayout();
            this.grpComment.SuspendLayout();
            this.grpTypePress.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.gridBindTo)).BeginInit();
            this.tabPage2.SuspendLayout();
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.DeviceBindingSource)).BeginInit();
            this.MenuBind.SuspendLayout();
            this.MenuLayout.SuspendLayout();
            this.grpSpaceNav.SuspendLayout();
            this.grpPilot.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.picturePilot)).BeginInit();
            this.grpTraveler.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            // 
            // pictureRight
            // 
            this.pictureRight.Image = ((System.Drawing.Image)(resources.GetObject("pictureRight.Image")));
            this.pictureRight.Location = new System.Drawing.Point(264, 117);
            this.pictureRight.Name = "pictureRight";
            this.pictureRight.Size = new System.Drawing.Size(18, 37);
            this.pictureRight.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.pictureRight.TabIndex = 72;
            this.pictureRight.TabStop = false;
            this.pictureRight.Tag = "Btn_1";
            // 
            // pictureLeft
            // 
            this.pictureLeft.Image = ((System.Drawing.Image)(resources.GetObject("pictureLeft.Image")));
            this.pictureLeft.Location = new System.Drawing.Point(28, 111);
            this.pictureLeft.Name = "pictureLeft";
            this.pictureLeft.Size = new System.Drawing.Size(23, 35);
            this.pictureLeft.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.pictureLeft.TabIndex = 71;
            this.pictureLeft.TabStop = false;
            this.pictureLeft.Tag = "Btn_0";
            // 
            // lbl_rZ
            // 
            this.lbl_rZ.BackColor = System.Drawing.Color.Transparent;
            this.lbl_rZ.Location = new System.Drawing.Point(749, 180);
            this.lbl_rZ.Name = "lbl_rZ";
            this.lbl_rZ.Size = new System.Drawing.Size(35, 12);
            this.lbl_rZ.TabIndex = 67;
            this.lbl_rZ.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // lbl_rY
            // 
            this.lbl_rY.BackColor = System.Drawing.Color.Transparent;
            this.lbl_rY.Location = new System.Drawing.Point(577, 165);
            this.lbl_rY.Name = "lbl_rY";
            this.lbl_rY.Size = new System.Drawing.Size(35, 12);
            this.lbl_rY.TabIndex = 66;
            this.lbl_rY.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // lbl_rX
            // 
            this.lbl_rX.BackColor = System.Drawing.Color.Transparent;
            this.lbl_rX.Location = new System.Drawing.Point(365, 159);
            this.lbl_rX.Name = "lbl_rX";
            this.lbl_rX.Size = new System.Drawing.Size(35, 12);
            this.lbl_rX.TabIndex = 65;
            this.lbl_rX.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // lbl_Z
            // 
            this.lbl_Z.BackColor = System.Drawing.Color.Transparent;
            this.lbl_Z.Location = new System.Drawing.Point(758, 15);
            this.lbl_Z.Name = "lbl_Z";
            this.lbl_Z.Size = new System.Drawing.Size(35, 13);
            this.lbl_Z.TabIndex = 64;
            this.lbl_Z.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // lbl_Y
            // 
            this.lbl_Y.BackColor = System.Drawing.Color.Transparent;
            this.lbl_Y.Location = new System.Drawing.Point(578, 34);
            this.lbl_Y.Name = "lbl_Y";
            this.lbl_Y.Size = new System.Drawing.Size(35, 13);
            this.lbl_Y.TabIndex = 63;
            this.lbl_Y.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // lbl_X
            // 
            this.lbl_X.BackColor = System.Drawing.Color.Transparent;
            this.lbl_X.Location = new System.Drawing.Point(350, 40);
            this.lbl_X.Name = "lbl_X";
            this.lbl_X.Size = new System.Drawing.Size(35, 12);
            this.lbl_X.TabIndex = 62;
            this.lbl_X.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // gridLayout
            // 
            this.gridLayout.AllowUserToAddRows = false;
            this.gridLayout.AllowUserToDeleteRows = false;
            this.gridLayout.AllowUserToResizeColumns = false;
            this.gridLayout.AllowUserToResizeRows = false;
            this.gridLayout.AutoGenerateColumns = false;
            this.gridLayout.BackgroundColor = System.Drawing.Color.WhiteSmoke;
            dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
            dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control;
            dataGridViewCellStyle1.Font = new System.Drawing.Font("Comic Sans MS", 9.75F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
            dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
            dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
            dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
            this.gridLayout.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
            this.gridLayout.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.gridLayout.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.profilNameDataGridViewTextBoxColumn});
            this.gridLayout.DataSource = this.layoutStructBindingSource;
            this.gridLayout.Location = new System.Drawing.Point(14, 179);
            this.gridLayout.MultiSelect = false;
            this.gridLayout.Name = "gridLayout";
            this.gridLayout.RowHeadersVisible = false;
            this.gridLayout.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            this.gridLayout.Size = new System.Drawing.Size(276, 158);
            this.gridLayout.TabIndex = 84;
            this.gridLayout.MouseClick += new System.Windows.Forms.MouseEventHandler(this.gridLayout_MouseClick);
            this.gridLayout.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.gridLayout_CellValueChanged);
            // 
            // profilNameDataGridViewTextBoxColumn
            // 
            this.profilNameDataGridViewTextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            this.profilNameDataGridViewTextBoxColumn.DataPropertyName = "Profil_Name";
            dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
            dataGridViewCellStyle2.BackColor = System.Drawing.Color.WhiteSmoke;
            this.profilNameDataGridViewTextBoxColumn.DefaultCellStyle = dataGridViewCellStyle2;
            this.profilNameDataGridViewTextBoxColumn.HeaderText = "Layout";
            this.profilNameDataGridViewTextBoxColumn.Name = "profilNameDataGridViewTextBoxColumn";
            this.profilNameDataGridViewTextBoxColumn.Resizable = System.Windows.Forms.DataGridViewTriState.False;
            this.profilNameDataGridViewTextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic;
            // 
            // layoutStructBindingSource
            // 
            this.layoutStructBindingSource.DataSource = typeof(RBC9___HID.LayoutStruct);
            this.layoutStructBindingSource.Sort = "";
            this.layoutStructBindingSource.PositionChanged += new System.EventHandler(this.layoutStructBindingSource_PositionChanged);
            // 
            // grpDeadZone
            // 
            this.grpDeadZone.BackColor = System.Drawing.Color.WhiteSmoke;
            this.grpDeadZone.Controls.Add(this.trkDeadZone);
            this.grpDeadZone.Controls.Add(this.txtDeadZone);
            this.grpDeadZone.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.grpDeadZone.Location = new System.Drawing.Point(38, 347);
            this.grpDeadZone.Name = "grpDeadZone";
            this.grpDeadZone.Size = new System.Drawing.Size(221, 52);
            this.grpDeadZone.TabIndex = 91;
            this.grpDeadZone.TabStop = false;
            this.grpDeadZone.Text = "DeadZone";
            // 
            // trkDeadZone
            // 
            this.trkDeadZone.AutoSize = false;
            this.trkDeadZone.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.layoutStructBindingSource, "DeadZone", true));
            this.trkDeadZone.Location = new System.Drawing.Point(45, 23);
            this.trkDeadZone.Maximum = 360;
            this.trkDeadZone.Name = "trkDeadZone";
            this.trkDeadZone.Size = new System.Drawing.Size(170, 23);
            this.trkDeadZone.TabIndex = 90;
            this.trkDeadZone.TickStyle = System.Windows.Forms.TickStyle.None;
            this.trkDeadZone.Scroll += new System.EventHandler(this.trkDeadZone_Scroll_1);
            // 
            // txtDeadZone
            // 
            this.txtDeadZone.BackColor = System.Drawing.Color.WhiteSmoke;
            this.txtDeadZone.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.layoutStructBindingSource, "DeadZone", true));
            this.txtDeadZone.Location = new System.Drawing.Point(15, 23);
            this.txtDeadZone.Name = "txtDeadZone";
            this.txtDeadZone.Size = new System.Drawing.Size(29, 23);
            this.txtDeadZone.TabIndex = 89;
            this.txtDeadZone.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
            // 
            // grpSpaceNavAxe
            // 
            this.grpSpaceNavAxe.BackColor = System.Drawing.Color.Transparent;
            this.grpSpaceNavAxe.Controls.Add(this.lblAxeDead);
            this.grpSpaceNavAxe.Controls.Add(this.lblMin);
            this.grpSpaceNavAxe.Controls.Add(this.label4);
            this.grpSpaceNavAxe.Controls.Add(this.label2);
            this.grpSpaceNavAxe.Controls.Add(this.trkAxeZone);
            this.grpSpaceNavAxe.Controls.Add(this.label1);
            this.grpSpaceNavAxe.Controls.Add(this.lblMax);
            this.grpSpaceNavAxe.Controls.Add(this.trkMaxVal);
            this.grpSpaceNavAxe.Controls.Add(this.trkMinVal);
            this.grpSpaceNavAxe.Controls.Add(this.cboAxePart);
            this.grpSpaceNavAxe.Controls.Add(this.chkInvert);
            this.grpSpaceNavAxe.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.grpSpaceNavAxe.Location = new System.Drawing.Point(13, 180);
            this.grpSpaceNavAxe.Name = "grpSpaceNavAxe";
            this.grpSpaceNavAxe.Size = new System.Drawing.Size(261, 120);
            this.grpSpaceNavAxe.TabIndex = 112;
            this.grpSpaceNavAxe.TabStop = false;
            this.grpSpaceNavAxe.Text = "Space Axe";
            // 
            // lblAxeDead
            // 
            this.lblAxeDead.AutoSize = true;
            this.lblAxeDead.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.lblAxeDead.Location = new System.Drawing.Point(76, 51);
            this.lblAxeDead.Name = "lblAxeDead";
            this.lblAxeDead.Size = new System.Drawing.Size(14, 15);
            this.lblAxeDead.TabIndex = 143;
            this.lblAxeDead.Text = "0";
            // 
            // lblMin
            // 
            this.lblMin.AutoSize = true;
            this.lblMin.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.layoutBindBindingSource, "MinVal", true));
            this.lblMin.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.lblMin.Location = new System.Drawing.Point(47, 75);
            this.lblMin.Name = "lblMin";
            this.lblMin.Size = new System.Drawing.Size(27, 15);
            this.lblMin.TabIndex = 114;
            this.lblMin.Text = "Min";
            // 
            // layoutBindBindingSource
            // 
            this.layoutBindBindingSource.DataSource = typeof(RBC9___HID.LayoutBind);
            this.layoutBindBindingSource.Filter = "";
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.label4.Location = new System.Drawing.Point(9, 51);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(59, 15);
            this.label4.TabIndex = 144;
            this.label4.Text = "DeadZone";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.label2.Location = new System.Drawing.Point(9, 98);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(30, 15);
            this.label2.TabIndex = 117;
            this.label2.Text = "Max";
            // 
            // trkAxeZone
            // 
            this.trkAxeZone.AutoSize = false;
            this.trkAxeZone.BackColor = System.Drawing.Color.WhiteSmoke;
            this.trkAxeZone.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.layoutBindBindingSource, "DeadZone", true));
            this.trkAxeZone.Location = new System.Drawing.Point(116, 54);
            this.trkAxeZone.Maximum = 150;
            this.trkAxeZone.Name = "trkAxeZone";
            this.trkAxeZone.Size = new System.Drawing.Size(102, 19);
            this.trkAxeZone.TabIndex = 142;
            this.trkAxeZone.TickStyle = System.Windows.Forms.TickStyle.None;
            this.trkAxeZone.Scroll += new System.EventHandler(this.trkAxeZone_Scroll);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.label1.Location = new System.Drawing.Point(9, 75);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(27, 15);
            this.label1.TabIndex = 116;
            this.label1.Text = "Min";
            // 
            // lblMax
            // 
            this.lblMax.AutoSize = true;
            this.lblMax.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.layoutBindBindingSource, "MaxVal", true));
            this.lblMax.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.lblMax.Location = new System.Drawing.Point(47, 98);
            this.lblMax.Name = "lblMax";
            this.lblMax.Size = new System.Drawing.Size(30, 15);
            this.lblMax.TabIndex = 115;
            this.lblMax.Text = "Max";
            // 
            // trkMaxVal
            // 
            this.trkMaxVal.AutoSize = false;
            this.trkMaxVal.BackColor = System.Drawing.Color.WhiteSmoke;
            this.trkMaxVal.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.layoutBindBindingSource, "MaxVal", true));
            this.trkMaxVal.Location = new System.Drawing.Point(83, 99);
            this.trkMaxVal.Maximum = 360;
            this.trkMaxVal.Name = "trkMaxVal";
            this.trkMaxVal.Size = new System.Drawing.Size(170, 19);
            this.trkMaxVal.TabIndex = 113;
            this.trkMaxVal.TickStyle = System.Windows.Forms.TickStyle.None;
            this.trkMaxVal.Scroll += new System.EventHandler(this.trkMaxVal_Scroll_1);
            // 
            // trkMinVal
            // 
            this.trkMinVal.AutoSize = false;
            this.trkMinVal.BackColor = System.Drawing.Color.WhiteSmoke;
            this.trkMinVal.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.layoutBindBindingSource, "MinVal", true));
            this.trkMinVal.Location = new System.Drawing.Point(83, 76);
            this.trkMinVal.Maximum = 360;
            this.trkMinVal.Name = "trkMinVal";
            this.trkMinVal.Size = new System.Drawing.Size(170, 19);
            this.trkMinVal.TabIndex = 112;
            this.trkMinVal.TickStyle = System.Windows.Forms.TickStyle.None;
            this.trkMinVal.Scroll += new System.EventHandler(this.trkMinVal_Scroll_1);
            // 
            // cboAxePart
            // 
            this.cboAxePart.BackColor = System.Drawing.SystemColors.Info;
            this.cboAxePart.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.layoutBindBindingSource, "AxePart", true));
            this.cboAxePart.DataSource = this.AxePartBindingSource;
            this.cboAxePart.DisplayMember = "Txt";
            this.cboAxePart.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboAxePart.FormattingEnabled = true;
            this.cboAxePart.Location = new System.Drawing.Point(115, 18);
            this.cboAxePart.Name = "cboAxePart";
            this.cboAxePart.Size = new System.Drawing.Size(103, 23);
            this.cboAxePart.TabIndex = 108;
            this.cboAxePart.ValueMember = "Id";
            // 
            // AxePartBindingSource
            // 
            this.AxePartBindingSource.DataSource = typeof(RBC9___HID.BaseLst);
            // 
            // chkInvert
            // 
            this.chkInvert.AutoSize = true;
            this.chkInvert.DataBindings.Add(new System.Windows.Forms.Binding("Checked", this.layoutBindBindingSource, "Invert", true));
            this.chkInvert.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.chkInvert.Location = new System.Drawing.Point(16, 20);
            this.chkInvert.Name = "chkInvert";
            this.chkInvert.Size = new System.Drawing.Size(59, 19);
            this.chkInvert.TabIndex = 104;
            this.chkInvert.Text = "Invert";
            this.chkInvert.UseVisualStyleBackColor = true;
            // 
            // cboKey5
            // 
            this.cboKey5.BackColor = System.Drawing.SystemColors.Info;
            this.cboKey5.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.layoutBindBindingSource, "BindTo_Key5", true));
            this.cboKey5.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboKey5.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.cboKey5.FormattingEnabled = true;
            this.cboKey5.Location = new System.Drawing.Point(183, 115);
            this.cboKey5.Name = "cboKey5";
            this.cboKey5.Size = new System.Drawing.Size(108, 23);
            this.cboKey5.TabIndex = 131;
            // 
            // grpSpaceNavBtn
            // 
            this.grpSpaceNavBtn.Controls.Add(this.chkInvertBtn);
            this.grpSpaceNavBtn.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.grpSpaceNavBtn.Location = new System.Drawing.Point(76, 209);
            this.grpSpaceNavBtn.Name = "grpSpaceNavBtn";
            this.grpSpaceNavBtn.Size = new System.Drawing.Size(117, 51);
            this.grpSpaceNavBtn.TabIndex = 114;
            this.grpSpaceNavBtn.TabStop = false;
            this.grpSpaceNavBtn.Text = "Space Button";
            // 
            // chkInvertBtn
            // 
            this.chkInvertBtn.AutoSize = true;
            this.chkInvertBtn.DataBindings.Add(new System.Windows.Forms.Binding("Checked", this.layoutBindBindingSource, "Invert", true));
            this.chkInvertBtn.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.chkInvertBtn.Location = new System.Drawing.Point(15, 26);
            this.chkInvertBtn.Name = "chkInvertBtn";
            this.chkInvertBtn.Size = new System.Drawing.Size(95, 19);
            this.chkInvertBtn.TabIndex = 104;
            this.chkInvertBtn.Text = "Invert Button";
            this.chkInvertBtn.UseVisualStyleBackColor = true;
            // 
            // grpTypeDelay
            // 
            this.grpTypeDelay.Controls.Add(this.lblTypeDelay);
            this.grpTypeDelay.Controls.Add(this.trkTypeDelay);
            this.grpTypeDelay.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.grpTypeDelay.Location = new System.Drawing.Point(422, 5);
            this.grpTypeDelay.Name = "grpTypeDelay";
            this.grpTypeDelay.Size = new System.Drawing.Size(169, 50);
            this.grpTypeDelay.TabIndex = 146;
            this.grpTypeDelay.TabStop = false;
            this.grpTypeDelay.Text = "Delay (ms)";
            // 
            // lblTypeDelay
            // 
            this.lblTypeDelay.AutoSize = true;
            this.lblTypeDelay.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.layoutBindBindingSource, "FromDelay", true));
            this.lblTypeDelay.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.lblTypeDelay.Location = new System.Drawing.Point(76, 12);
            this.lblTypeDelay.Name = "lblTypeDelay";
            this.lblTypeDelay.Size = new System.Drawing.Size(11, 15);
            this.lblTypeDelay.TabIndex = 145;
            this.lblTypeDelay.Text = "-";
            // 
            // trkTypeDelay
            // 
            this.trkTypeDelay.AutoSize = false;
            this.trkTypeDelay.BackColor = System.Drawing.Color.WhiteSmoke;
            this.trkTypeDelay.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.layoutBindBindingSource, "FromDelay", true));
            this.trkTypeDelay.Location = new System.Drawing.Point(6, 29);
            this.trkTypeDelay.Maximum = 2500;
            this.trkTypeDelay.Name = "trkTypeDelay";
            this.trkTypeDelay.Size = new System.Drawing.Size(154, 19);
            this.trkTypeDelay.TabIndex = 143;
            this.trkTypeDelay.TickStyle = System.Windows.Forms.TickStyle.None;
            this.trkTypeDelay.Scroll += new System.EventHandler(this.trkBtnDelay_Scroll);
            // 
            // cboPressType
            // 
            this.cboPressType.BackColor = System.Drawing.SystemColors.Info;
            this.cboPressType.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.layoutBindBindingSource, "FromType", true));
            this.cboPressType.DataSource = this.PressTypeBindingSource;
            this.cboPressType.DisplayMember = "Txt";
            this.cboPressType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboPressType.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.cboPressType.FormattingEnabled = true;
            this.cboPressType.Location = new System.Drawing.Point(9, 18);
            this.cboPressType.Name = "cboPressType";
            this.cboPressType.Size = new System.Drawing.Size(98, 23);
            this.cboPressType.TabIndex = 109;
            this.cboPressType.ValueMember = "Id";
            this.cboPressType.SelectionChangeCommitted += new System.EventHandler(this.cboBtnType_SelectionChangeCommitted);
            // 
            // PressTypeBindingSource
            // 
            this.PressTypeBindingSource.DataSource = typeof(RBC9___HID.BaseLst);
            this.PressTypeBindingSource.CurrentChanged += new System.EventHandler(this.BtnTypeBindingSource_CurrentChanged);
            // 
            // cboBintTo
            // 
            this.cboBintTo.BackColor = System.Drawing.SystemColors.Info;
            this.cboBintTo.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.layoutBindBindingSource, "BindTo", true));
            this.cboBintTo.DataSource = this.BindToBindingSource;
            this.cboBintTo.DisplayMember = "Txt";
            this.cboBintTo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboBintTo.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.cboBintTo.FormattingEnabled = true;
            this.cboBintTo.Location = new System.Drawing.Point(9, 21);
            this.cboBintTo.Name = "cboBintTo";
            this.cboBintTo.Size = new System.Drawing.Size(103, 23);
            this.cboBintTo.TabIndex = 115;
            this.cboBintTo.ValueMember = "Id";
            this.cboBintTo.SelectionChangeCommitted += new System.EventHandler(this.cboBintTo_SelectionChangeCommitted);
            // 
            // BindToBindingSource
            // 
            this.BindToBindingSource.DataSource = typeof(RBC9___HID.BaseLst);
            // 
            // cboJoyAxe
            // 
            this.cboJoyAxe.BackColor = System.Drawing.SystemColors.Info;
            this.cboJoyAxe.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.layoutBindBindingSource, "BindTo_JoyAxe", true));
            this.cboJoyAxe.DataSource = this.JoyAxeBindingSource;
            this.cboJoyAxe.DisplayMember = "Txt";
            this.cboJoyAxe.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboJoyAxe.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.cboJoyAxe.FormattingEnabled = true;
            this.cboJoyAxe.Location = new System.Drawing.Point(37, 22);
            this.cboJoyAxe.Name = "cboJoyAxe";
            this.cboJoyAxe.Size = new System.Drawing.Size(64, 23);
            this.cboJoyAxe.TabIndex = 116;
            this.cboJoyAxe.ValueMember = "Id";
            // 
            // JoyAxeBindingSource
            // 
            this.JoyAxeBindingSource.DataSource = typeof(RBC9___HID.BaseLst);
            // 
            // cboJoyPOV
            // 
            this.cboJoyPOV.BackColor = System.Drawing.SystemColors.Info;
            this.cboJoyPOV.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.layoutBindBindingSource, "BindTo_JoyPov", true));
            this.cboJoyPOV.DataSource = this.JoyPOVBindingSource;
            this.cboJoyPOV.DisplayMember = "Txt";
            this.cboJoyPOV.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboJoyPOV.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.cboJoyPOV.FormattingEnabled = true;
            this.cboJoyPOV.Location = new System.Drawing.Point(23, 22);
            this.cboJoyPOV.Name = "cboJoyPOV";
            this.cboJoyPOV.Size = new System.Drawing.Size(95, 23);
            this.cboJoyPOV.TabIndex = 117;
            this.cboJoyPOV.ValueMember = "Id";
            // 
            // JoyPOVBindingSource
            // 
            this.JoyPOVBindingSource.DataSource = typeof(RBC9___HID.BaseLst);
            // 
            // cboJoyBtn
            // 
            this.cboJoyBtn.BackColor = System.Drawing.SystemColors.Info;
            this.cboJoyBtn.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.layoutBindBindingSource, "BindTo_JoyBtn", true));
            this.cboJoyBtn.DataSource = this.JoyBtnBindingSource;
            this.cboJoyBtn.DisplayMember = "Txt";
            this.cboJoyBtn.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboJoyBtn.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.cboJoyBtn.FormattingEnabled = true;
            this.cboJoyBtn.Location = new System.Drawing.Point(50, 22);
            this.cboJoyBtn.Name = "cboJoyBtn";
            this.cboJoyBtn.Size = new System.Drawing.Size(42, 23);
            this.cboJoyBtn.TabIndex = 118;
            this.cboJoyBtn.ValueMember = "Id";
            // 
            // JoyBtnBindingSource
            // 
            this.JoyBtnBindingSource.DataSource = typeof(RBC9___HID.BaseLst);
            // 
            // cboMouBtn
            // 
            this.cboMouBtn.BackColor = System.Drawing.SystemColors.Info;
            this.cboMouBtn.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.layoutBindBindingSource, "BindTo_MouBtn", true));
            this.cboMouBtn.DataSource = this.MouBtnBindingSource;
            this.cboMouBtn.DisplayMember = "Txt";
            this.cboMouBtn.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboMouBtn.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.cboMouBtn.FormattingEnabled = true;
            this.cboMouBtn.Location = new System.Drawing.Point(27, 22);
            this.cboMouBtn.Name = "cboMouBtn";
            this.cboMouBtn.Size = new System.Drawing.Size(81, 23);
            this.cboMouBtn.TabIndex = 119;
            this.cboMouBtn.ValueMember = "Id";
            // 
            // MouBtnBindingSource
            // 
            this.MouBtnBindingSource.DataSource = typeof(RBC9___HID.BaseLst);
            // 
            // trkMouSensi
            // 
            this.trkMouSensi.AutoSize = false;
            this.trkMouSensi.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.layoutBindBindingSource, "BindTo_MouSensi", true));
            this.trkMouSensi.Location = new System.Drawing.Point(6, 37);
            this.trkMouSensi.Maximum = 200;
            this.trkMouSensi.Name = "trkMouSensi";
            this.trkMouSensi.Size = new System.Drawing.Size(215, 23);
            this.trkMouSensi.TabIndex = 120;
            this.trkMouSensi.TickStyle = System.Windows.Forms.TickStyle.None;
            this.trkMouSensi.Value = 10;
            this.trkMouSensi.Scroll += new System.EventHandler(this.trkMouSensi_Scroll);
            // 
            // lblValSensi
            // 
            this.lblValSensi.AutoSize = true;
            this.lblValSensi.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.layoutBindBindingSource, "BindTo_MouSensi", true));
            this.lblValSensi.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.lblValSensi.Location = new System.Drawing.Point(112, 19);
            this.lblValSensi.Name = "lblValSensi";
            this.lblValSensi.Size = new System.Drawing.Size(27, 15);
            this.lblValSensi.TabIndex = 121;
            this.lblValSensi.Text = "Min";
            this.lblValSensi.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // lblMouSensi
            // 
            this.lblMouSensi.AutoSize = true;
            this.lblMouSensi.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.lblMouSensi.Location = new System.Drawing.Point(45, 19);
            this.lblMouSensi.Name = "lblMouSensi";
            this.lblMouSensi.Size = new System.Drawing.Size(64, 15);
            this.lblMouSensi.TabIndex = 122;
            this.lblMouSensi.Text = "Sensitivity";
            this.lblMouSensi.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // lblMouSensiTaux
            // 
            this.lblMouSensiTaux.AutoSize = true;
            this.lblMouSensiTaux.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.lblMouSensiTaux.Location = new System.Drawing.Point(137, 19);
            this.lblMouSensiTaux.Name = "lblMouSensiTaux";
            this.lblMouSensiTaux.Size = new System.Drawing.Size(16, 15);
            this.lblMouSensiTaux.TabIndex = 123;
            this.lblMouSensiTaux.Text = "%";
            this.lblMouSensiTaux.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // cboKey1
            // 
            this.cboKey1.BackColor = System.Drawing.SystemColors.Info;
            this.cboKey1.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.layoutBindBindingSource, "BindTo_Key1", true));
            this.cboKey1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboKey1.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.cboKey1.FormattingEnabled = true;
            this.cboKey1.Location = new System.Drawing.Point(183, 15);
            this.cboKey1.Name = "cboKey1";
            this.cboKey1.Size = new System.Drawing.Size(108, 23);
            this.cboKey1.TabIndex = 127;
            // 
            // cboKey2
            // 
            this.cboKey2.BackColor = System.Drawing.SystemColors.Info;
            this.cboKey2.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.layoutBindBindingSource, "BindTo_Key2", true));
            this.cboKey2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboKey2.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.cboKey2.FormattingEnabled = true;
            this.cboKey2.Location = new System.Drawing.Point(183, 40);
            this.cboKey2.Name = "cboKey2";
            this.cboKey2.Size = new System.Drawing.Size(108, 23);
            this.cboKey2.TabIndex = 128;
            // 
            // cboKey3
            // 
            this.cboKey3.BackColor = System.Drawing.SystemColors.Info;
            this.cboKey3.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.layoutBindBindingSource, "BindTo_Key3", true));
            this.cboKey3.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboKey3.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.cboKey3.FormattingEnabled = true;
            this.cboKey3.Location = new System.Drawing.Point(183, 65);
            this.cboKey3.Name = "cboKey3";
            this.cboKey3.Size = new System.Drawing.Size(108, 23);
            this.cboKey3.TabIndex = 129;
            // 
            // cboKey4
            // 
            this.cboKey4.BackColor = System.Drawing.SystemColors.Info;
            this.cboKey4.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.layoutBindBindingSource, "BindTo_Key4", true));
            this.cboKey4.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboKey4.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.cboKey4.FormattingEnabled = true;
            this.cboKey4.Location = new System.Drawing.Point(183, 90);
            this.cboKey4.Name = "cboKey4";
            this.cboKey4.Size = new System.Drawing.Size(108, 23);
            this.cboKey4.TabIndex = 130;
            // 
            // cboKey
            // 
            this.cboKey.BackColor = System.Drawing.SystemColors.Info;
            this.cboKey.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.layoutBindBindingSource, "BindTo_Key", true));
            this.cboKey.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboKey.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.cboKey.FormattingEnabled = true;
            this.cboKey.Location = new System.Drawing.Point(38, 34);
            this.cboKey.Name = "cboKey";
            this.cboKey.Size = new System.Drawing.Size(95, 23);
            this.cboKey.TabIndex = 132;
            // 
            // chkRepeat
            // 
            this.chkRepeat.AutoSize = true;
            this.chkRepeat.DataBindings.Add(new System.Windows.Forms.Binding("Checked", this.layoutBindBindingSource, "BindTo_KeyRepeat", true));
            this.chkRepeat.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.chkRepeat.Location = new System.Drawing.Point(15, 79);
            this.chkRepeat.Name = "chkRepeat";
            this.chkRepeat.Size = new System.Drawing.Size(107, 19);
            this.chkRepeat.TabIndex = 133;
            this.chkRepeat.Text = "Repeat Key (ms)";
            this.chkRepeat.UseVisualStyleBackColor = true;
            // 
            // trkRepeat
            // 
            this.trkRepeat.AutoSize = false;
            this.trkRepeat.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.layoutBindBindingSource, "BindTo_KeyDelay", true));
            this.trkRepeat.Location = new System.Drawing.Point(5, 104);
            this.trkRepeat.Maximum = 2000;
            this.trkRepeat.Name = "trkRepeat";
            this.trkRepeat.Size = new System.Drawing.Size(170, 23);
            this.trkRepeat.TabIndex = 134;
            this.trkRepeat.TickStyle = System.Windows.Forms.TickStyle.None;
            this.trkRepeat.Value = 10;
            this.trkRepeat.Scroll += new System.EventHandler(this.trkRepeat_Scroll);
            // 
            // lblRepeatDelay
            // 
            this.lblRepeatDelay.AutoSize = true;
            this.lblRepeatDelay.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.layoutBindBindingSource, "BindTo_KeyDelay", true));
            this.lblRepeatDelay.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.lblRepeatDelay.Location = new System.Drawing.Point(125, 80);
            this.lblRepeatDelay.Name = "lblRepeatDelay";
            this.lblRepeatDelay.Size = new System.Drawing.Size(25, 15);
            this.lblRepeatDelay.TabIndex = 135;
            this.lblRepeatDelay.Text = "???";
            this.lblRepeatDelay.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // grpLayout
            // 
            this.grpLayout.Controls.Add(this.cboProfil);
            this.grpLayout.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.grpLayout.Location = new System.Drawing.Point(286, 180);
            this.grpLayout.Name = "grpLayout";
            this.grpLayout.Size = new System.Drawing.Size(304, 52);
            this.grpLayout.TabIndex = 136;
            this.grpLayout.TabStop = false;
            this.grpLayout.Text = "Select Layout";
            // 
            // cboProfil
            // 
            this.cboProfil.BackColor = System.Drawing.SystemColors.Info;
            this.cboProfil.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.layoutBindBindingSource, "BindTo_ProfilId", true));
            this.cboProfil.DataSource = this.ProfilLstBindingSource;
            this.cboProfil.DisplayMember = "Profil_Name";
            this.cboProfil.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboProfil.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.cboProfil.FormattingEnabled = true;
            this.cboProfil.Location = new System.Drawing.Point(9, 22);
            this.cboProfil.Name = "cboProfil";
            this.cboProfil.Size = new System.Drawing.Size(285, 23);
            this.cboProfil.TabIndex = 124;
            this.cboProfil.ValueMember = "Profil_Id";
            // 
            // ProfilLstBindingSource
            // 
            this.ProfilLstBindingSource.DataSource = typeof(RBC9___HID.LayoutStruct);
            // 
            // grpMouBtn
            // 
            this.grpMouBtn.Controls.Add(this.cboMouBtn);
            this.grpMouBtn.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.grpMouBtn.Location = new System.Drawing.Point(355, 180);
            this.grpMouBtn.Name = "grpMouBtn";
            this.grpMouBtn.Size = new System.Drawing.Size(134, 52);
            this.grpMouBtn.TabIndex = 140;
            this.grpMouBtn.TabStop = false;
            this.grpMouBtn.Text = "Select Mouse Button";
            // 
            // grpJoyBtn
            // 
            this.grpJoyBtn.Controls.Add(this.cboJoyBtn);
            this.grpJoyBtn.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.grpJoyBtn.Location = new System.Drawing.Point(353, 180);
            this.grpJoyBtn.Name = "grpJoyBtn";
            this.grpJoyBtn.Size = new System.Drawing.Size(147, 52);
            this.grpJoyBtn.TabIndex = 139;
            this.grpJoyBtn.TabStop = false;
            this.grpJoyBtn.Text = "Select Joystick Button";
            // 
            // grpJoyPov
            // 
            this.grpJoyPov.Controls.Add(this.cboJoyPOV);
            this.grpJoyPov.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.grpJoyPov.Location = new System.Drawing.Point(354, 180);
            this.grpJoyPov.Name = "grpJoyPov";
            this.grpJoyPov.Size = new System.Drawing.Size(140, 52);
            this.grpJoyPov.TabIndex = 139;
            this.grpJoyPov.TabStop = false;
            this.grpJoyPov.Text = "Select Joystick POV";
            // 
            // grpJoyAxe
            // 
            this.grpJoyAxe.Controls.Add(this.cboJoyAxe);
            this.grpJoyAxe.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.grpJoyAxe.Location = new System.Drawing.Point(355, 180);
            this.grpJoyAxe.Name = "grpJoyAxe";
            this.grpJoyAxe.Size = new System.Drawing.Size(139, 52);
            this.grpJoyAxe.TabIndex = 138;
            this.grpJoyAxe.TabStop = false;
            this.grpJoyAxe.Text = "Select Joystick Axe";
            // 
            // grpMouseSensi
            // 
            this.grpMouseSensi.Controls.Add(this.trkMouSensi);
            this.grpMouseSensi.Controls.Add(this.lblMouSensi);
            this.grpMouseSensi.Controls.Add(this.lblValSensi);
            this.grpMouseSensi.Controls.Add(this.lblMouSensiTaux);
            this.grpMouseSensi.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.grpMouseSensi.Location = new System.Drawing.Point(311, 177);
            this.grpMouseSensi.Name = "grpMouseSensi";
            this.grpMouseSensi.Size = new System.Drawing.Size(227, 72);
            this.grpMouseSensi.TabIndex = 140;
            this.grpMouseSensi.TabStop = false;
            // 
            // grpKey
            // 
            this.grpKey.Controls.Add(this.cboKey);
            this.grpKey.Controls.Add(this.chkRepeat);
            this.grpKey.Controls.Add(this.trkRepeat);
            this.grpKey.Controls.Add(this.lblRepeatDelay);
            this.grpKey.Controls.Add(this.cboKey5);
            this.grpKey.Controls.Add(this.cboKey1);
            this.grpKey.Controls.Add(this.cboKey4);
            this.grpKey.Controls.Add(this.cboKey2);
            this.grpKey.Controls.Add(this.cboKey3);
            this.grpKey.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.grpKey.Location = new System.Drawing.Point(284, 165);
            this.grpKey.Name = "grpKey";
            this.grpKey.Size = new System.Drawing.Size(306, 144);
            this.grpKey.TabIndex = 137;
            this.grpKey.TabStop = false;
            // 
            // grpWWW
            // 
            this.grpWWW.Controls.Add(this.cboWWW);
            this.grpWWW.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.grpWWW.Location = new System.Drawing.Point(345, 180);
            this.grpWWW.Name = "grpWWW";
            this.grpWWW.Size = new System.Drawing.Size(164, 52);
            this.grpWWW.TabIndex = 162;
            this.grpWWW.TabStop = false;
            this.grpWWW.Text = "Select Special Key";
            // 
            // cboWWW
            // 
            this.cboWWW.BackColor = System.Drawing.SystemColors.Info;
            this.cboWWW.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.layoutBindBindingSource, "BindTo_WWW", true));
            this.cboWWW.DataSource = this.WWWBindingSource;
            this.cboWWW.DisplayMember = "Txt";
            this.cboWWW.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboWWW.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.cboWWW.FormattingEnabled = true;
            this.cboWWW.Location = new System.Drawing.Point(27, 22);
            this.cboWWW.Name = "cboWWW";
            this.cboWWW.Size = new System.Drawing.Size(111, 23);
            this.cboWWW.TabIndex = 119;
            this.cboWWW.ValueMember = "Id";
            // 
            // WWWBindingSource
            // 
            this.WWWBindingSource.DataSource = typeof(RBC9___HID.BaseLst);
            // 
            // grpBindType
            // 
            this.grpBindType.Controls.Add(this.cboBintTo);
            this.grpBindType.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.grpBindType.Location = new System.Drawing.Point(365, 111);
            this.grpBindType.Name = "grpBindType";
            this.grpBindType.Size = new System.Drawing.Size(119, 52);
            this.grpBindType.TabIndex = 140;
            this.grpBindType.TabStop = false;
            this.grpBindType.Text = "Bind Type";
            // 
            // cboDefault
            // 
            this.cboDefault.BackColor = System.Drawing.SystemColors.Info;
            this.cboDefault.DataSource = this.DefaultLayoutBindingSource;
            this.cboDefault.DisplayMember = "Profil_Name";
            this.cboDefault.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboDefault.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.cboDefault.FormattingEnabled = true;
            this.cboDefault.Location = new System.Drawing.Point(12, 20);
            this.cboDefault.Name = "cboDefault";
            this.cboDefault.Size = new System.Drawing.Size(253, 23);
            this.cboDefault.TabIndex = 142;
            this.cboDefault.ValueMember = "Profil_Id";
            this.cboDefault.SelectedIndexChanged += new System.EventHandler(this.cboDefault_SelectedIndexChanged);
            // 
            // DefaultLayoutBindingSource
            // 
            this.DefaultLayoutBindingSource.DataSource = typeof(RBC9___HID.LayoutStruct);
            // 
            // grpDefault
            // 
            this.grpDefault.Controls.Add(this.cboDefault);
            this.grpDefault.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.grpDefault.Location = new System.Drawing.Point(14, 114);
            this.grpDefault.Name = "grpDefault";
            this.grpDefault.Size = new System.Drawing.Size(278, 49);
            this.grpDefault.TabIndex = 143;
            this.grpDefault.TabStop = false;
            this.grpDefault.Text = "Default Layout";
            // 
            // pictureSpaceNav
            // 
            this.pictureSpaceNav.Image = ((System.Drawing.Image)(resources.GetObject("pictureSpaceNav.Image")));
            this.pictureSpaceNav.Location = new System.Drawing.Point(11, 9);
            this.pictureSpaceNav.Name = "pictureSpaceNav";
            this.pictureSpaceNav.Size = new System.Drawing.Size(287, 274);
            this.pictureSpaceNav.TabIndex = 68;
            this.pictureSpaceNav.TabStop = false;
            // 
            // radioAxe_1
            // 
            this.radioAxe_1.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioAxe_1.AutoSize = true;
            this.radioAxe_1.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioAxe_1.FlatAppearance.BorderColor = System.Drawing.Color.White;
            this.radioAxe_1.FlatAppearance.BorderSize = 0;
            this.radioAxe_1.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioAxe_1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioAxe_1.Image = ((System.Drawing.Image)(resources.GetObject("radioAxe_1.Image")));
            this.radioAxe_1.Location = new System.Drawing.Point(572, 29);
            this.radioAxe_1.Name = "radioAxe_1";
            this.radioAxe_1.Size = new System.Drawing.Size(119, 102);
            this.radioAxe_1.TabIndex = 145;
            this.radioAxe_1.TabStop = true;
            this.radioAxe_1.Tag = "Axe_1";
            this.radioAxe_1.UseVisualStyleBackColor = true;
            this.radioAxe_1.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioAxe_0
            // 
            this.radioAxe_0.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioAxe_0.AutoSize = true;
            this.radioAxe_0.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioAxe_0.FlatAppearance.BorderSize = 0;
            this.radioAxe_0.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioAxe_0.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioAxe_0.Image = ((System.Drawing.Image)(resources.GetObject("radioAxe_0.Image")));
            this.radioAxe_0.Location = new System.Drawing.Point(344, 35);
            this.radioAxe_0.Name = "radioAxe_0";
            this.radioAxe_0.Size = new System.Drawing.Size(183, 95);
            this.radioAxe_0.TabIndex = 146;
            this.radioAxe_0.TabStop = true;
            this.radioAxe_0.Tag = "Axe_0";
            this.radioAxe_0.UseVisualStyleBackColor = true;
            this.radioAxe_0.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioAxe_2
            // 
            this.radioAxe_2.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioAxe_2.AutoSize = true;
            this.radioAxe_2.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioAxe_2.FlatAppearance.BorderSize = 0;
            this.radioAxe_2.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioAxe_2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioAxe_2.Image = ((System.Drawing.Image)(resources.GetObject("radioAxe_2.Image")));
            this.radioAxe_2.Location = new System.Drawing.Point(752, 7);
            this.radioAxe_2.Name = "radioAxe_2";
            this.radioAxe_2.Size = new System.Drawing.Size(114, 147);
            this.radioAxe_2.TabIndex = 147;
            this.radioAxe_2.TabStop = true;
            this.radioAxe_2.Tag = "Axe_2";
            this.radioAxe_2.UseVisualStyleBackColor = true;
            this.radioAxe_2.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioAxe_4
            // 
            this.radioAxe_4.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioAxe_4.AutoSize = true;
            this.radioAxe_4.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioAxe_4.FlatAppearance.BorderSize = 0;
            this.radioAxe_4.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioAxe_4.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioAxe_4.Image = ((System.Drawing.Image)(resources.GetObject("radioAxe_4.Image")));
            this.radioAxe_4.Location = new System.Drawing.Point(569, 156);
            this.radioAxe_4.Name = "radioAxe_4";
            this.radioAxe_4.Size = new System.Drawing.Size(124, 117);
            this.radioAxe_4.TabIndex = 148;
            this.radioAxe_4.TabStop = true;
            this.radioAxe_4.Tag = "Axe_3";
            this.radioAxe_4.UseVisualStyleBackColor = true;
            this.radioAxe_4.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioAxe_3
            // 
            this.radioAxe_3.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioAxe_3.AutoSize = true;
            this.radioAxe_3.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioAxe_3.FlatAppearance.BorderSize = 0;
            this.radioAxe_3.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioAxe_3.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioAxe_3.Image = ((System.Drawing.Image)(resources.GetObject("radioAxe_3.Image")));
            this.radioAxe_3.Location = new System.Drawing.Point(358, 151);
            this.radioAxe_3.Name = "radioAxe_3";
            this.radioAxe_3.Size = new System.Drawing.Size(153, 124);
            this.radioAxe_3.TabIndex = 149;
            this.radioAxe_3.TabStop = true;
            this.radioAxe_3.Tag = "Axe_4";
            this.radioAxe_3.UseVisualStyleBackColor = true;
            this.radioAxe_3.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioAxe_5
            // 
            this.radioAxe_5.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioAxe_5.AutoSize = true;
            this.radioAxe_5.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioAxe_5.FlatAppearance.BorderSize = 0;
            this.radioAxe_5.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioAxe_5.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioAxe_5.Image = ((System.Drawing.Image)(resources.GetObject("radioAxe_5.Image")));
            this.radioAxe_5.Location = new System.Drawing.Point(743, 174);
            this.radioAxe_5.Name = "radioAxe_5";
            this.radioAxe_5.Size = new System.Drawing.Size(153, 123);
            this.radioAxe_5.TabIndex = 150;
            this.radioAxe_5.TabStop = true;
            this.radioAxe_5.Tag = "Axe_5";
            this.radioAxe_5.UseVisualStyleBackColor = true;
            this.radioAxe_5.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_1_Nav
            // 
            this.radioBtn_1_Nav.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_1_Nav.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_1_Nav.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_1_Nav.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_1_Nav.FlatAppearance.BorderSize = 0;
            this.radioBtn_1_Nav.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_1_Nav.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_1_Nav.Image = ((System.Drawing.Image)(resources.GetObject("radioBtn_1_Nav.Image")));
            this.radioBtn_1_Nav.ImageAlign = System.Drawing.ContentAlignment.TopRight;
            this.radioBtn_1_Nav.Location = new System.Drawing.Point(246, 96);
            this.radioBtn_1_Nav.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_1_Nav.Name = "radioBtn_1_Nav";
            this.radioBtn_1_Nav.Size = new System.Drawing.Size(54, 72);
            this.radioBtn_1_Nav.TabIndex = 151;
            this.radioBtn_1_Nav.TabStop = true;
            this.radioBtn_1_Nav.Tag = "Btn_1";
            this.radioBtn_1_Nav.UseMnemonic = false;
            this.radioBtn_1_Nav.UseVisualStyleBackColor = false;
            this.radioBtn_1_Nav.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_0_Nav
            // 
            this.radioBtn_0_Nav.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_0_Nav.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_0_Nav.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_0_Nav.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_0_Nav.FlatAppearance.BorderSize = 0;
            this.radioBtn_0_Nav.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_0_Nav.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_0_Nav.Image = ((System.Drawing.Image)(resources.GetObject("radioBtn_0_Nav.Image")));
            this.radioBtn_0_Nav.ImageAlign = System.Drawing.ContentAlignment.TopLeft;
            this.radioBtn_0_Nav.Location = new System.Drawing.Point(12, 83);
            this.radioBtn_0_Nav.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_0_Nav.Name = "radioBtn_0_Nav";
            this.radioBtn_0_Nav.Size = new System.Drawing.Size(55, 81);
            this.radioBtn_0_Nav.TabIndex = 152;
            this.radioBtn_0_Nav.TabStop = true;
            this.radioBtn_0_Nav.Tag = "Btn_0";
            this.radioBtn_0_Nav.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_0_Nav.UseMnemonic = false;
            this.radioBtn_0_Nav.UseVisualStyleBackColor = false;
            this.radioBtn_0_Nav.Click += new System.EventHandler(this.radio_Click);
            // 
            // btnApply
            // 
            this.btnApply.AutoSize = true;
            this.btnApply.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
            this.btnApply.Font = new System.Drawing.Font("Comic Sans MS", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnApply.Image = ((System.Drawing.Image)(resources.GetObject("btnApply.Image")));
            this.btnApply.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.btnApply.Location = new System.Drawing.Point(377, 660);
            this.btnApply.Name = "btnApply";
            this.btnApply.Size = new System.Drawing.Size(97, 41);
            this.btnApply.TabIndex = 154;
            this.btnApply.Text = "Apply";
            this.btnApply.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.btnApply.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
            this.btnApply.UseVisualStyleBackColor = false;
            this.btnApply.Click += new System.EventHandler(this.btnApply_Click);
            // 
            // btnCancel
            // 
            this.btnCancel.AutoSize = true;
            this.btnCancel.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
            this.btnCancel.Font = new System.Drawing.Font("Comic Sans MS", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnCancel.Image = ((System.Drawing.Image)(resources.GetObject("btnCancel.Image")));
            this.btnCancel.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.btnCancel.Location = new System.Drawing.Point(791, 660);
            this.btnCancel.Name = "btnCancel";
            this.btnCancel.Size = new System.Drawing.Size(97, 41);
            this.btnCancel.TabIndex = 155;
            this.btnCancel.Text = "Cancel";
            this.btnCancel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.btnCancel.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
            this.btnCancel.UseVisualStyleBackColor = false;
            this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
            // 
            // gridAppAuto
            // 
            this.gridAppAuto.AllowUserToAddRows = false;
            this.gridAppAuto.AllowUserToDeleteRows = false;
            this.gridAppAuto.AllowUserToResizeColumns = false;
            this.gridAppAuto.AllowUserToResizeRows = false;
            this.gridAppAuto.AutoGenerateColumns = false;
            this.gridAppAuto.BackgroundColor = System.Drawing.Color.WhiteSmoke;
            dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
            dataGridViewCellStyle3.BackColor = System.Drawing.SystemColors.Control;
            dataGridViewCellStyle3.Font = new System.Drawing.Font("Comic Sans MS", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            dataGridViewCellStyle3.ForeColor = System.Drawing.SystemColors.WindowText;
            dataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight;
            dataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
            dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
            this.gridAppAuto.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle3;
            this.gridAppAuto.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.gridAppAuto.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.txtDataGridViewTextBoxColumn});
            this.gridAppAuto.DataSource = this.layoutAppAutoBindingSource;
            this.gridAppAuto.Location = new System.Drawing.Point(155, 31);
            this.gridAppAuto.Name = "gridAppAuto";
            this.gridAppAuto.RowHeadersVisible = false;
            this.gridAppAuto.Size = new System.Drawing.Size(275, 194);
            this.gridAppAuto.TabIndex = 0;
            // 
            // txtDataGridViewTextBoxColumn
            // 
            this.txtDataGridViewTextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            this.txtDataGridViewTextBoxColumn.DataPropertyName = "Txt";
            dataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
            dataGridViewCellStyle4.BackColor = System.Drawing.Color.WhiteSmoke;
            dataGridViewCellStyle4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.txtDataGridViewTextBoxColumn.DefaultCellStyle = dataGridViewCellStyle4;
            this.txtDataGridViewTextBoxColumn.HeaderText = "Appication Executable Name";
            this.txtDataGridViewTextBoxColumn.Name = "txtDataGridViewTextBoxColumn";
            // 
            // layoutAppAutoBindingSource
            // 
            this.layoutAppAutoBindingSource.DataSource = typeof(RBC9___HID.BaseLst);
            // 
            // tabControl1
            // 
            this.tabControl1.Controls.Add(this.tabPage1);
            this.tabControl1.Controls.Add(this.tabPage2);
            this.tabControl1.Font = new System.Drawing.Font("Comic Sans MS", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.tabControl1.Location = new System.Drawing.Point(324, 296);
            this.tabControl1.Margin = new System.Windows.Forms.Padding(0);
            this.tabControl1.Name = "tabControl1";
            this.tabControl1.SelectedIndex = 0;
            this.tabControl1.Size = new System.Drawing.Size(614, 348);
            this.tabControl1.TabIndex = 158;
            // 
            // tabPage1
            // 
            this.tabPage1.BackColor = System.Drawing.Color.WhiteSmoke;
            this.tabPage1.Controls.Add(this.grpComment);
            this.tabPage1.Controls.Add(this.grpTypeDelay);
            this.tabPage1.Controls.Add(this.grpTypePress);
            this.tabPage1.Controls.Add(this.grpMouseSensi);
            this.tabPage1.Controls.Add(this.grpMouBtn);
            this.tabPage1.Controls.Add(this.grpJoyPov);
            this.tabPage1.Controls.Add(this.gridBindTo);
            this.tabPage1.Controls.Add(this.grpJoyAxe);
            this.tabPage1.Controls.Add(this.grpJoyBtn);
            this.tabPage1.Controls.Add(this.grpBindType);
            this.tabPage1.Controls.Add(this.grpWWW);
            this.tabPage1.Controls.Add(this.grpSpaceNavBtn);
            this.tabPage1.Controls.Add(this.grpLayout);
            this.tabPage1.Controls.Add(this.grpKey);
            this.tabPage1.Controls.Add(this.grpSpaceNavAxe);
            this.tabPage1.Location = new System.Drawing.Point(4, 25);
            this.tabPage1.Margin = new System.Windows.Forms.Padding(0);
            this.tabPage1.Name = "tabPage1";
            this.tabPage1.Size = new System.Drawing.Size(606, 319);
            this.tabPage1.TabIndex = 0;
            this.tabPage1.Text = "Bind";
            // 
            // grpComment
            // 
            this.grpComment.Controls.Add(this.txtComment);
            this.grpComment.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.grpComment.Location = new System.Drawing.Point(284, 56);
            this.grpComment.Name = "grpComment";
            this.grpComment.Size = new System.Drawing.Size(306, 53);
            this.grpComment.TabIndex = 165;
            this.grpComment.TabStop = false;
            this.grpComment.Text = "Comment";
            // 
            // txtComment
            // 
            this.txtComment.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.layoutBindBindingSource, "Comment", true));
            this.txtComment.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.txtComment.Location = new System.Drawing.Point(10, 19);
            this.txtComment.MaxLength = 44;
            this.txtComment.Name = "txtComment";
            this.txtComment.Size = new System.Drawing.Size(288, 23);
            this.txtComment.TabIndex = 164;
            // 
            // grpTypePress
            // 
            this.grpTypePress.Controls.Add(this.cboPressType);
            this.grpTypePress.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.grpTypePress.Location = new System.Drawing.Point(285, 5);
            this.grpTypePress.Name = "grpTypePress";
            this.grpTypePress.Size = new System.Drawing.Size(119, 50);
            this.grpTypePress.TabIndex = 163;
            this.grpTypePress.TabStop = false;
            this.grpTypePress.Text = "Press Type";
            // 
            // gridBindTo
            // 
            this.gridBindTo.AllowUserToAddRows = false;
            this.gridBindTo.AllowUserToDeleteRows = false;
            this.gridBindTo.AllowUserToResizeColumns = false;
            this.gridBindTo.AllowUserToResizeRows = false;
            this.gridBindTo.AutoGenerateColumns = false;
            this.gridBindTo.BackgroundColor = System.Drawing.Color.WhiteSmoke;
            dataGridViewCellStyle5.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
            dataGridViewCellStyle5.BackColor = System.Drawing.SystemColors.Control;
            dataGridViewCellStyle5.Font = new System.Drawing.Font("Comic Sans MS", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            dataGridViewCellStyle5.ForeColor = System.Drawing.SystemColors.WindowText;
            dataGridViewCellStyle5.SelectionBackColor = System.Drawing.SystemColors.Highlight;
            dataGridViewCellStyle5.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
            dataGridViewCellStyle5.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
            this.gridBindTo.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle5;
            this.gridBindTo.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.gridBindTo.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.bindToTxtDataGridViewTextBoxColumn1,
            this.Comment});
            this.gridBindTo.DataSource = this.layoutBindBindingSource;
            this.gridBindTo.Location = new System.Drawing.Point(9, 17);
            this.gridBindTo.MultiSelect = false;
            this.gridBindTo.Name = "gridBindTo";
            this.gridBindTo.RowHeadersVisible = false;
            this.gridBindTo.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
            this.gridBindTo.Size = new System.Drawing.Size(265, 152);
            this.gridBindTo.TabIndex = 141;
            this.gridBindTo.MouseClick += new System.Windows.Forms.MouseEventHandler(this.gridBindTo_MouseClick);
            this.gridBindTo.SelectionChanged += new System.EventHandler(this.gridBindTo_SelectionChanged);
            // 
            // bindToTxtDataGridViewTextBoxColumn1
            // 
            this.bindToTxtDataGridViewTextBoxColumn1.DataPropertyName = "BindTo_Txt";
            dataGridViewCellStyle6.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
            dataGridViewCellStyle6.BackColor = System.Drawing.Color.WhiteSmoke;
            dataGridViewCellStyle6.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.bindToTxtDataGridViewTextBoxColumn1.DefaultCellStyle = dataGridViewCellStyle6;
            this.bindToTxtDataGridViewTextBoxColumn1.HeaderText = "Bind To";
            this.bindToTxtDataGridViewTextBoxColumn1.Name = "bindToTxtDataGridViewTextBoxColumn1";
            this.bindToTxtDataGridViewTextBoxColumn1.ReadOnly = true;
            this.bindToTxtDataGridViewTextBoxColumn1.Width = 135;
            // 
            // Comment
            // 
            this.Comment.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            this.Comment.DataPropertyName = "Comment";
            dataGridViewCellStyle7.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F);
            this.Comment.DefaultCellStyle = dataGridViewCellStyle7;
            this.Comment.HeaderText = "Comment";
            this.Comment.Name = "Comment";
            this.Comment.ReadOnly = true;
            // 
            // tabPage2
            // 
            this.tabPage2.BackColor = System.Drawing.Color.WhiteSmoke;
            this.tabPage2.Controls.Add(this.btnDelAppAuto);
            this.tabPage2.Controls.Add(this.btnAddAppAuto);
            this.tabPage2.Controls.Add(this.gridAppAuto);
            this.tabPage2.Location = new System.Drawing.Point(4, 25);
            this.tabPage2.Name = "tabPage2";
            this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
            this.tabPage2.RightToLeft = System.Windows.Forms.RightToLeft.No;
            this.tabPage2.Size = new System.Drawing.Size(606, 319);
            this.tabPage2.TabIndex = 1;
            this.tabPage2.Text = "Application AutoSwitch";
            // 
            // btnDelAppAuto
            // 
            this.btnDelAppAuto.Font = new System.Drawing.Font("Comic Sans MS", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnDelAppAuto.Location = new System.Drawing.Point(334, 253);
            this.btnDelAppAuto.Name = "btnDelAppAuto";
            this.btnDelAppAuto.Size = new System.Drawing.Size(55, 27);
            this.btnDelAppAuto.TabIndex = 95;
            this.btnDelAppAuto.Text = "Del";
            this.btnDelAppAuto.UseVisualStyleBackColor = true;
            this.btnDelAppAuto.Click += new System.EventHandler(this.btnDelAppAuto_Click);
            // 
            // btnAddAppAuto
            // 
            this.btnAddAppAuto.Font = new System.Drawing.Font("Comic Sans MS", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnAddAppAuto.Location = new System.Drawing.Point(200, 253);
            this.btnAddAppAuto.Name = "btnAddAppAuto";
            this.btnAddAppAuto.Size = new System.Drawing.Size(55, 27);
            this.btnAddAppAuto.TabIndex = 96;
            this.btnAddAppAuto.Text = "Add";
            this.btnAddAppAuto.UseVisualStyleBackColor = true;
            this.btnAddAppAuto.Click += new System.EventHandler(this.btnAddAppAuto_Click);
            // 
            // chkAutoApp
            // 
            this.chkAutoApp.AutoSize = true;
            this.chkAutoApp.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.chkAutoApp.Location = new System.Drawing.Point(26, 80);
            this.chkAutoApp.Name = "chkAutoApp";
            this.chkAutoApp.Size = new System.Drawing.Size(104, 19);
            this.chkAutoApp.TabIndex = 159;
            this.chkAutoApp.Text = "AutoSwitch On";
            this.chkAutoApp.UseVisualStyleBackColor = true;
            this.chkAutoApp.CheckedChanged += new System.EventHandler(this.chkAutoApp_CheckedChanged);
            // 
            // groupBox1
            // 
            this.groupBox1.BackColor = System.Drawing.Color.WhiteSmoke;
            this.groupBox1.Controls.Add(this.groupBox2);
            this.groupBox1.Controls.Add(this.chkIcon);
            this.groupBox1.Controls.Add(this.chkInfoBulle);
            this.groupBox1.Controls.Add(this.chkAutoApp);
            this.groupBox1.Controls.Add(this.grpDefault);
            this.groupBox1.Controls.Add(this.gridLayout);
            this.groupBox1.Controls.Add(this.grpDeadZone);
            this.groupBox1.Location = new System.Drawing.Point(8, 290);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(309, 411);
            this.groupBox1.TabIndex = 160;
            this.groupBox1.TabStop = false;
            // 
            // groupBox2
            // 
            this.groupBox2.Controls.Add(this.cboDevice);
            this.groupBox2.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.groupBox2.Location = new System.Drawing.Point(53, 9);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(186, 49);
            this.groupBox2.TabIndex = 144;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "3DConnexion Device";
            // 
            // cboDevice
            // 
            this.cboDevice.BackColor = System.Drawing.SystemColors.Info;
            this.cboDevice.DataSource = this.DeviceBindingSource;
            this.cboDevice.DisplayMember = "Txt";
            this.cboDevice.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboDevice.Font = new System.Drawing.Font("Comic Sans MS", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))));
            this.cboDevice.FormattingEnabled = true;
            this.cboDevice.Location = new System.Drawing.Point(6, 20);
            this.cboDevice.Name = "cboDevice";
            this.cboDevice.Size = new System.Drawing.Size(174, 24);
            this.cboDevice.TabIndex = 162;
            this.cboDevice.ValueMember = "Id";
            this.cboDevice.SelectedIndexChanged += new System.EventHandler(this.cboDevice_SelectedIndexChanged);
            // 
            // DeviceBindingSource
            // 
            this.DeviceBindingSource.DataSource = typeof(RBC9___HID.BaseLst);
            // 
            // chkIcon
            // 
            this.chkIcon.AutoSize = true;
            this.chkIcon.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.chkIcon.Location = new System.Drawing.Point(174, 94);
            this.chkIcon.Name = "chkIcon";
            this.chkIcon.Size = new System.Drawing.Size(95, 19);
            this.chkIcon.TabIndex = 161;
            this.chkIcon.Text = "Animate Icon";
            this.chkIcon.UseVisualStyleBackColor = true;
            this.chkIcon.CheckedChanged += new System.EventHandler(this.chkIcon_CheckedChanged);
            // 
            // chkInfoBulle
            // 
            this.chkInfoBulle.AutoSize = true;
            this.chkInfoBulle.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.chkInfoBulle.Location = new System.Drawing.Point(174, 70);
            this.chkInfoBulle.Name = "chkInfoBulle";
            this.chkInfoBulle.Size = new System.Drawing.Size(105, 19);
            this.chkInfoBulle.TabIndex = 160;
            this.chkInfoBulle.Text = "ToolTip Balloon";
            this.chkInfoBulle.UseVisualStyleBackColor = true;
            this.chkInfoBulle.CheckedChanged += new System.EventHandler(this.chkInfoBulle_CheckedChanged);
            // 
            // btnCalib
            // 
            this.btnCalib.AutoSize = true;
            this.btnCalib.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
            this.btnCalib.Font = new System.Drawing.Font("Comic Sans MS", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnCalib.Image = ((System.Drawing.Image)(resources.GetObject("btnCalib.Image")));
            this.btnCalib.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.btnCalib.Location = new System.Drawing.Point(574, 660);
            this.btnCalib.Name = "btnCalib";
            this.btnCalib.Size = new System.Drawing.Size(105, 41);
            this.btnCalib.TabIndex = 161;
            this.btnCalib.Text = "Calibrate";
            this.btnCalib.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.btnCalib.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
            this.btnCalib.UseVisualStyleBackColor = false;
            this.btnCalib.Click += new System.EventHandler(this.btnCalib_Click);
            // 
            // MenuBind
            // 
            this.MenuBind.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.MenuBindAdd,
            this.MenuBindDel,
            this.MenuBindSeparator,
            this.MenuBindCopy,
            this.MenuBindPaste});
            this.MenuBind.Name = "contextMenuCopyBind";
            this.MenuBind.Size = new System.Drawing.Size(103, 98);
            // 
            // MenuBindAdd
            // 
            this.MenuBindAdd.Name = "MenuBindAdd";
            this.MenuBindAdd.Size = new System.Drawing.Size(102, 22);
            this.MenuBindAdd.Text = "Add";
            this.MenuBindAdd.Click += new System.EventHandler(this.MenuBindAdd_Click);
            // 
            // MenuBindDel
            // 
            this.MenuBindDel.Name = "MenuBindDel";
            this.MenuBindDel.Size = new System.Drawing.Size(102, 22);
            this.MenuBindDel.Text = "Del";
            this.MenuBindDel.Click += new System.EventHandler(this.MenuBindDel_Click);
            // 
            // MenuBindSeparator
            // 
            this.MenuBindSeparator.Name = "MenuBindSeparator";
            this.MenuBindSeparator.Size = new System.Drawing.Size(99, 6);
            // 
            // MenuBindCopy
            // 
            this.MenuBindCopy.Name = "MenuBindCopy";
            this.MenuBindCopy.Size = new System.Drawing.Size(102, 22);
            this.MenuBindCopy.Text = "Copy";
            this.MenuBindCopy.Click += new System.EventHandler(this.MenuBindCopy_Click);
            // 
            // MenuBindPaste
            // 
            this.MenuBindPaste.Name = "MenuBindPaste";
            this.MenuBindPaste.Size = new System.Drawing.Size(102, 22);
            this.MenuBindPaste.Text = "Paste";
            this.MenuBindPaste.Click += new System.EventHandler(this.MenuBindPaste_Click);
            // 
            // MenuLayout
            // 
            this.MenuLayout.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.MenuLayoutAdd,
            this.MenuLayoutDel,
            this.MenuLayoutSeparator,
            this.MenuLayoutDuplicate,
            this.MenuLayoutExport,
            this.MenuLayoutImport});
            this.MenuLayout.Name = "contextMenuCopyBind";
            this.MenuLayout.Size = new System.Drawing.Size(143, 120);
            // 
            // MenuLayoutAdd
            // 
            this.MenuLayoutAdd.Name = "MenuLayoutAdd";
            this.MenuLayoutAdd.Size = new System.Drawing.Size(142, 22);
            this.MenuLayoutAdd.Text = "Add";
            this.MenuLayoutAdd.Click += new System.EventHandler(this.MenuLayoutAdd_Click);
            // 
            // MenuLayoutDel
            // 
            this.MenuLayoutDel.Name = "MenuLayoutDel";
            this.MenuLayoutDel.Size = new System.Drawing.Size(142, 22);
            this.MenuLayoutDel.Text = "Del";
            this.MenuLayoutDel.Click += new System.EventHandler(this.MenuLayoutDel_Click);
            // 
            // MenuLayoutSeparator
            // 
            this.MenuLayoutSeparator.Name = "MenuLayoutSeparator";
            this.MenuLayoutSeparator.Size = new System.Drawing.Size(139, 6);
            // 
            // MenuLayoutDuplicate
            // 
            this.MenuLayoutDuplicate.Name = "MenuLayoutDuplicate";
            this.MenuLayoutDuplicate.Size = new System.Drawing.Size(142, 22);
            this.MenuLayoutDuplicate.Text = "Duplicate";
            this.MenuLayoutDuplicate.Click += new System.EventHandler(this.MenuLayoutDuplicate_Click);
            // 
            // MenuLayoutExport
            // 
            this.MenuLayoutExport.Name = "MenuLayoutExport";
            this.MenuLayoutExport.Size = new System.Drawing.Size(142, 22);
            this.MenuLayoutExport.Text = "Export Binds";
            this.MenuLayoutExport.Click += new System.EventHandler(this.MenuLayoutExport_Click);
            // 
            // MenuLayoutImport
            // 
            this.MenuLayoutImport.Name = "MenuLayoutImport";
            this.MenuLayoutImport.Size = new System.Drawing.Size(142, 22);
            this.MenuLayoutImport.Text = "Import Binds";
            this.MenuLayoutImport.Click += new System.EventHandler(this.MenuLayoutImport_Click);
            // 
            // openFileBind
            // 
            this.openFileBind.Filter = "Bind File|*.bind";
            // 
            // saveFileBind
            // 
            this.saveFileBind.Filter = "Bind File|*.bind";
            // 
            // grpSpaceNav
            // 
            this.grpSpaceNav.Controls.Add(this.radioBtn_Nul_Nav);
            this.grpSpaceNav.Controls.Add(this.pictureLeft);
            this.grpSpaceNav.Controls.Add(this.pictureRight);
            this.grpSpaceNav.Controls.Add(this.radioBtn_1_Nav);
            this.grpSpaceNav.Controls.Add(this.radioBtn_0_Nav);
            this.grpSpaceNav.Controls.Add(this.pictureSpaceNav);
            this.grpSpaceNav.Location = new System.Drawing.Point(8, 4);
            this.grpSpaceNav.Name = "grpSpaceNav";
            this.grpSpaceNav.Size = new System.Drawing.Size(309, 289);
            this.grpSpaceNav.TabIndex = 162;
            this.grpSpaceNav.TabStop = false;
            // 
            // radioBtn_Nul_Nav
            // 
            this.radioBtn_Nul_Nav.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_Nul_Nav.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_Nul_Nav.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_Nul_Nav.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_Nul_Nav.FlatAppearance.BorderSize = 0;
            this.radioBtn_Nul_Nav.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_Nul_Nav.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_Nul_Nav.ImageAlign = System.Drawing.ContentAlignment.TopRight;
            this.radioBtn_Nul_Nav.Location = new System.Drawing.Point(128, 212);
            this.radioBtn_Nul_Nav.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_Nul_Nav.Name = "radioBtn_Nul_Nav";
            this.radioBtn_Nul_Nav.Size = new System.Drawing.Size(47, 38);
            this.radioBtn_Nul_Nav.TabIndex = 153;
            this.radioBtn_Nul_Nav.TabStop = true;
            this.radioBtn_Nul_Nav.Tag = "Btn_Null";
            this.radioBtn_Nul_Nav.Text = "Null Btn";
            this.radioBtn_Nul_Nav.UseMnemonic = false;
            this.radioBtn_Nul_Nav.UseVisualStyleBackColor = false;
            this.radioBtn_Nul_Nav.Visible = false;
            // 
            // grpPilot
            // 
            this.grpPilot.Controls.Add(this.radioBtn_20_Pil);
            this.grpPilot.Controls.Add(this.radioBtn_19_Pil);
            this.grpPilot.Controls.Add(this.radioBtn_18_Pil);
            this.grpPilot.Controls.Add(this.radioBtn_17_Pil);
            this.grpPilot.Controls.Add(this.radioBtn_16_Pil);
            this.grpPilot.Controls.Add(this.radioBtn_15_Pil);
            this.grpPilot.Controls.Add(this.radioBtn_14_Pil);
            this.grpPilot.Controls.Add(this.radioBtn_13_Pil);
            this.grpPilot.Controls.Add(this.radioBtn_12_Pil);
            this.grpPilot.Controls.Add(this.radioBtn_11_Pil);
            this.grpPilot.Controls.Add(this.radioBtn_10_Pil);
            this.grpPilot.Controls.Add(this.radioBtn_9_Pil);
            this.grpPilot.Controls.Add(this.radioBtn_8_Pil);
            this.grpPilot.Controls.Add(this.radioBtn_7_Pil);
            this.grpPilot.Controls.Add(this.radioBtn_6_Pil);
            this.grpPilot.Controls.Add(this.radioBtn_5_Pil);
            this.grpPilot.Controls.Add(this.radioBtn_4_Pil);
            this.grpPilot.Controls.Add(this.radioBtn_3_Pil);
            this.grpPilot.Controls.Add(this.radioBtn_2_Pil);
            this.grpPilot.Controls.Add(this.radioBtn_1_Pil);
            this.grpPilot.Controls.Add(this.radioBtn_Nul_Pil);
            this.grpPilot.Controls.Add(this.radioBtn_0_Pil);
            this.grpPilot.Controls.Add(this.picturePilot);
            this.grpPilot.Location = new System.Drawing.Point(8, 4);
            this.grpPilot.Name = "grpPilot";
            this.grpPilot.Size = new System.Drawing.Size(309, 289);
            this.grpPilot.TabIndex = 163;
            this.grpPilot.TabStop = false;
            // 
            // radioBtn_20_Pil
            // 
            this.radioBtn_20_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_20_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_20_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_20_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_20_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_20_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_20_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_20_Pil.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_20_Pil.ImageList = this.PilotImageList;
            this.radioBtn_20_Pil.Location = new System.Drawing.Point(235, 184);
            this.radioBtn_20_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_20_Pil.Name = "radioBtn_20_Pil";
            this.radioBtn_20_Pil.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_20_Pil.TabIndex = 176;
            this.radioBtn_20_Pil.TabStop = true;
            this.radioBtn_20_Pil.Tag = "Btn_20";
            this.radioBtn_20_Pil.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_20_Pil.UseMnemonic = false;
            this.radioBtn_20_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_20_Pil.Click += new System.EventHandler(this.radio_Click);
            // 
            // PilotImageList
            // 
            this.PilotImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("PilotImageList.ImageStream")));
            this.PilotImageList.TransparentColor = System.Drawing.Color.Transparent;
            this.PilotImageList.Images.SetKeyName(0, "Btn_Pilot Off.jpg");
            this.PilotImageList.Images.SetKeyName(1, "Btn_Pilot On.jpg");
            // 
            // radioBtn_19_Pil
            // 
            this.radioBtn_19_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_19_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_19_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_19_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_19_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_19_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_19_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_19_Pil.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_19_Pil.ImageList = this.PilotImageList;
            this.radioBtn_19_Pil.Location = new System.Drawing.Point(277, 248);
            this.radioBtn_19_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_19_Pil.Name = "radioBtn_19_Pil";
            this.radioBtn_19_Pil.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_19_Pil.TabIndex = 175;
            this.radioBtn_19_Pil.TabStop = true;
            this.radioBtn_19_Pil.Tag = "Btn_19";
            this.radioBtn_19_Pil.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_19_Pil.UseMnemonic = false;
            this.radioBtn_19_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_19_Pil.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_18_Pil
            // 
            this.radioBtn_18_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_18_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_18_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_18_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_18_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_18_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_18_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_18_Pil.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_18_Pil.ImageList = this.PilotImageList;
            this.radioBtn_18_Pil.Location = new System.Drawing.Point(247, 248);
            this.radioBtn_18_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_18_Pil.Name = "radioBtn_18_Pil";
            this.radioBtn_18_Pil.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_18_Pil.TabIndex = 174;
            this.radioBtn_18_Pil.TabStop = true;
            this.radioBtn_18_Pil.Tag = "Btn_18";
            this.radioBtn_18_Pil.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_18_Pil.UseMnemonic = false;
            this.radioBtn_18_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_18_Pil.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_17_Pil
            // 
            this.radioBtn_17_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_17_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_17_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_17_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_17_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_17_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_17_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_17_Pil.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_17_Pil.ImageList = this.PilotImageList;
            this.radioBtn_17_Pil.Location = new System.Drawing.Point(217, 248);
            this.radioBtn_17_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_17_Pil.Name = "radioBtn_17_Pil";
            this.radioBtn_17_Pil.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_17_Pil.TabIndex = 173;
            this.radioBtn_17_Pil.TabStop = true;
            this.radioBtn_17_Pil.Tag = "Btn_17";
            this.radioBtn_17_Pil.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_17_Pil.UseMnemonic = false;
            this.radioBtn_17_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_17_Pil.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_16_Pil
            // 
            this.radioBtn_16_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_16_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_16_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_16_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_16_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_16_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_16_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_16_Pil.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_16_Pil.ImageList = this.PilotImageList;
            this.radioBtn_16_Pil.Location = new System.Drawing.Point(187, 248);
            this.radioBtn_16_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_16_Pil.Name = "radioBtn_16_Pil";
            this.radioBtn_16_Pil.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_16_Pil.TabIndex = 172;
            this.radioBtn_16_Pil.TabStop = true;
            this.radioBtn_16_Pil.Tag = "Btn_16";
            this.radioBtn_16_Pil.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_16_Pil.UseMnemonic = false;
            this.radioBtn_16_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_16_Pil.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_15_Pil
            // 
            this.radioBtn_15_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_15_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_15_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_15_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_15_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_15_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_15_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_15_Pil.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_15_Pil.ImageList = this.PilotImageList;
            this.radioBtn_15_Pil.Location = new System.Drawing.Point(157, 248);
            this.radioBtn_15_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_15_Pil.Name = "radioBtn_15_Pil";
            this.radioBtn_15_Pil.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_15_Pil.TabIndex = 171;
            this.radioBtn_15_Pil.TabStop = true;
            this.radioBtn_15_Pil.Tag = "Btn_15";
            this.radioBtn_15_Pil.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_15_Pil.UseMnemonic = false;
            this.radioBtn_15_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_15_Pil.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_14_Pil
            // 
            this.radioBtn_14_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_14_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_14_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_14_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_14_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_14_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_14_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_14_Pil.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_14_Pil.ImageList = this.PilotImageList;
            this.radioBtn_14_Pil.Location = new System.Drawing.Point(127, 248);
            this.radioBtn_14_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_14_Pil.Name = "radioBtn_14_Pil";
            this.radioBtn_14_Pil.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_14_Pil.TabIndex = 170;
            this.radioBtn_14_Pil.TabStop = true;
            this.radioBtn_14_Pil.Tag = "Btn_14";
            this.radioBtn_14_Pil.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_14_Pil.UseMnemonic = false;
            this.radioBtn_14_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_14_Pil.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_13_Pil
            // 
            this.radioBtn_13_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_13_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_13_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_13_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_13_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_13_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_13_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_13_Pil.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_13_Pil.ImageList = this.PilotImageList;
            this.radioBtn_13_Pil.Location = new System.Drawing.Point(97, 248);
            this.radioBtn_13_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_13_Pil.Name = "radioBtn_13_Pil";
            this.radioBtn_13_Pil.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_13_Pil.TabIndex = 169;
            this.radioBtn_13_Pil.TabStop = true;
            this.radioBtn_13_Pil.Tag = "Btn_13";
            this.radioBtn_13_Pil.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_13_Pil.UseMnemonic = false;
            this.radioBtn_13_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_13_Pil.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_12_Pil
            // 
            this.radioBtn_12_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_12_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_12_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_12_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_12_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_12_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_12_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_12_Pil.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_12_Pil.ImageList = this.PilotImageList;
            this.radioBtn_12_Pil.Location = new System.Drawing.Point(67, 248);
            this.radioBtn_12_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_12_Pil.Name = "radioBtn_12_Pil";
            this.radioBtn_12_Pil.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_12_Pil.TabIndex = 168;
            this.radioBtn_12_Pil.TabStop = true;
            this.radioBtn_12_Pil.Tag = "Btn_12";
            this.radioBtn_12_Pil.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_12_Pil.UseMnemonic = false;
            this.radioBtn_12_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_12_Pil.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_11_Pil
            // 
            this.radioBtn_11_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_11_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_11_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_11_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_11_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_11_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_11_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_11_Pil.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_11_Pil.ImageList = this.PilotImageList;
            this.radioBtn_11_Pil.Location = new System.Drawing.Point(37, 248);
            this.radioBtn_11_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_11_Pil.Name = "radioBtn_11_Pil";
            this.radioBtn_11_Pil.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_11_Pil.TabIndex = 167;
            this.radioBtn_11_Pil.TabStop = true;
            this.radioBtn_11_Pil.Tag = "Btn_11";
            this.radioBtn_11_Pil.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_11_Pil.UseMnemonic = false;
            this.radioBtn_11_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_11_Pil.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_10_Pil
            // 
            this.radioBtn_10_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_10_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_10_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_10_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_10_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_10_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_10_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_10_Pil.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_10_Pil.ImageList = this.PilotImageList;
            this.radioBtn_10_Pil.Location = new System.Drawing.Point(7, 248);
            this.radioBtn_10_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_10_Pil.Name = "radioBtn_10_Pil";
            this.radioBtn_10_Pil.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_10_Pil.TabIndex = 166;
            this.radioBtn_10_Pil.TabStop = true;
            this.radioBtn_10_Pil.Tag = "Btn_10";
            this.radioBtn_10_Pil.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_10_Pil.UseMnemonic = false;
            this.radioBtn_10_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_10_Pil.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_9_Pil
            // 
            this.radioBtn_9_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_9_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_9_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_9_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_9_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_9_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_9_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_9_Pil.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_9_Pil.ImageList = this.PilotImageList;
            this.radioBtn_9_Pil.Location = new System.Drawing.Point(274, 16);
            this.radioBtn_9_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_9_Pil.Name = "radioBtn_9_Pil";
            this.radioBtn_9_Pil.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_9_Pil.TabIndex = 165;
            this.radioBtn_9_Pil.TabStop = true;
            this.radioBtn_9_Pil.Tag = "Btn_9";
            this.radioBtn_9_Pil.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_9_Pil.UseMnemonic = false;
            this.radioBtn_9_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_9_Pil.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_8_Pil
            // 
            this.radioBtn_8_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_8_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_8_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_8_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_8_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_8_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_8_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_8_Pil.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_8_Pil.ImageList = this.PilotImageList;
            this.radioBtn_8_Pil.Location = new System.Drawing.Point(244, 16);
            this.radioBtn_8_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_8_Pil.Name = "radioBtn_8_Pil";
            this.radioBtn_8_Pil.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_8_Pil.TabIndex = 164;
            this.radioBtn_8_Pil.TabStop = true;
            this.radioBtn_8_Pil.Tag = "Btn_8";
            this.radioBtn_8_Pil.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_8_Pil.UseMnemonic = false;
            this.radioBtn_8_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_8_Pil.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_7_Pil
            // 
            this.radioBtn_7_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_7_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_7_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_7_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_7_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_7_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_7_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_7_Pil.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_7_Pil.ImageList = this.PilotImageList;
            this.radioBtn_7_Pil.Location = new System.Drawing.Point(214, 16);
            this.radioBtn_7_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_7_Pil.Name = "radioBtn_7_Pil";
            this.radioBtn_7_Pil.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_7_Pil.TabIndex = 163;
            this.radioBtn_7_Pil.TabStop = true;
            this.radioBtn_7_Pil.Tag = "Btn_7";
            this.radioBtn_7_Pil.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_7_Pil.UseMnemonic = false;
            this.radioBtn_7_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_7_Pil.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_6_Pil
            // 
            this.radioBtn_6_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_6_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_6_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_6_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_6_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_6_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_6_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_6_Pil.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_6_Pil.ImageList = this.PilotImageList;
            this.radioBtn_6_Pil.Location = new System.Drawing.Point(184, 16);
            this.radioBtn_6_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_6_Pil.Name = "radioBtn_6_Pil";
            this.radioBtn_6_Pil.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_6_Pil.TabIndex = 162;
            this.radioBtn_6_Pil.TabStop = true;
            this.radioBtn_6_Pil.Tag = "Btn_6";
            this.radioBtn_6_Pil.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_6_Pil.UseMnemonic = false;
            this.radioBtn_6_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_6_Pil.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_5_Pil
            // 
            this.radioBtn_5_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_5_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_5_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_5_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_5_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_5_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_5_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_5_Pil.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_5_Pil.ImageList = this.PilotImageList;
            this.radioBtn_5_Pil.Location = new System.Drawing.Point(154, 16);
            this.radioBtn_5_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_5_Pil.Name = "radioBtn_5_Pil";
            this.radioBtn_5_Pil.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_5_Pil.TabIndex = 161;
            this.radioBtn_5_Pil.TabStop = true;
            this.radioBtn_5_Pil.Tag = "Btn_5";
            this.radioBtn_5_Pil.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_5_Pil.UseMnemonic = false;
            this.radioBtn_5_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_5_Pil.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_4_Pil
            // 
            this.radioBtn_4_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_4_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_4_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_4_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_4_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_4_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_4_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_4_Pil.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_4_Pil.ImageList = this.PilotImageList;
            this.radioBtn_4_Pil.Location = new System.Drawing.Point(124, 16);
            this.radioBtn_4_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_4_Pil.Name = "radioBtn_4_Pil";
            this.radioBtn_4_Pil.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_4_Pil.TabIndex = 160;
            this.radioBtn_4_Pil.TabStop = true;
            this.radioBtn_4_Pil.Tag = "Btn_4";
            this.radioBtn_4_Pil.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_4_Pil.UseMnemonic = false;
            this.radioBtn_4_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_4_Pil.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_3_Pil
            // 
            this.radioBtn_3_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_3_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_3_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_3_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_3_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_3_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_3_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_3_Pil.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_3_Pil.ImageList = this.PilotImageList;
            this.radioBtn_3_Pil.Location = new System.Drawing.Point(94, 16);
            this.radioBtn_3_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_3_Pil.Name = "radioBtn_3_Pil";
            this.radioBtn_3_Pil.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_3_Pil.TabIndex = 159;
            this.radioBtn_3_Pil.TabStop = true;
            this.radioBtn_3_Pil.Tag = "Btn_3";
            this.radioBtn_3_Pil.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_3_Pil.UseMnemonic = false;
            this.radioBtn_3_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_3_Pil.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_2_Pil
            // 
            this.radioBtn_2_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_2_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_2_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_2_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_2_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_2_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_2_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_2_Pil.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_2_Pil.ImageList = this.PilotImageList;
            this.radioBtn_2_Pil.Location = new System.Drawing.Point(64, 16);
            this.radioBtn_2_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_2_Pil.Name = "radioBtn_2_Pil";
            this.radioBtn_2_Pil.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_2_Pil.TabIndex = 158;
            this.radioBtn_2_Pil.TabStop = true;
            this.radioBtn_2_Pil.Tag = "Btn_2";
            this.radioBtn_2_Pil.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_2_Pil.UseMnemonic = false;
            this.radioBtn_2_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_2_Pil.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_1_Pil
            // 
            this.radioBtn_1_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_1_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_1_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_1_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_1_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_1_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_1_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_1_Pil.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_1_Pil.ImageList = this.PilotImageList;
            this.radioBtn_1_Pil.Location = new System.Drawing.Point(34, 16);
            this.radioBtn_1_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_1_Pil.Name = "radioBtn_1_Pil";
            this.radioBtn_1_Pil.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_1_Pil.TabIndex = 157;
            this.radioBtn_1_Pil.TabStop = true;
            this.radioBtn_1_Pil.Tag = "Btn_1";
            this.radioBtn_1_Pil.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_1_Pil.UseMnemonic = false;
            this.radioBtn_1_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_1_Pil.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_Nul_Pil
            // 
            this.radioBtn_Nul_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_Nul_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_Nul_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_Nul_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_Nul_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_Nul_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_Nul_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_Nul_Pil.ImageAlign = System.Drawing.ContentAlignment.TopRight;
            this.radioBtn_Nul_Pil.Location = new System.Drawing.Point(131, 125);
            this.radioBtn_Nul_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_Nul_Pil.Name = "radioBtn_Nul_Pil";
            this.radioBtn_Nul_Pil.Size = new System.Drawing.Size(47, 38);
            this.radioBtn_Nul_Pil.TabIndex = 156;
            this.radioBtn_Nul_Pil.TabStop = true;
            this.radioBtn_Nul_Pil.Tag = "Btn_Null";
            this.radioBtn_Nul_Pil.Text = "Null Btn";
            this.radioBtn_Nul_Pil.UseMnemonic = false;
            this.radioBtn_Nul_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_Nul_Pil.Visible = false;
            // 
            // radioBtn_0_Pil
            // 
            this.radioBtn_0_Pil.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_0_Pil.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_0_Pil.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_0_Pil.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_0_Pil.FlatAppearance.BorderSize = 0;
            this.radioBtn_0_Pil.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_0_Pil.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_0_Pil.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_0_Pil.ImageList = this.PilotImageList;
            this.radioBtn_0_Pil.Location = new System.Drawing.Point(4, 16);
            this.radioBtn_0_Pil.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_0_Pil.Name = "radioBtn_0_Pil";
            this.radioBtn_0_Pil.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_0_Pil.TabIndex = 153;
            this.radioBtn_0_Pil.TabStop = true;
            this.radioBtn_0_Pil.Tag = "Btn_0";
            this.radioBtn_0_Pil.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_0_Pil.UseMnemonic = false;
            this.radioBtn_0_Pil.UseVisualStyleBackColor = false;
            this.radioBtn_0_Pil.Click += new System.EventHandler(this.radio_Click);
            // 
            // picturePilot
            // 
            this.picturePilot.Image = ((System.Drawing.Image)(resources.GetObject("picturePilot.Image")));
            this.picturePilot.Location = new System.Drawing.Point(7, 57);
            this.picturePilot.Name = "picturePilot";
            this.picturePilot.Size = new System.Drawing.Size(290, 184);
            this.picturePilot.TabIndex = 0;
            this.picturePilot.TabStop = false;
            // 
            // radioBtn_Nul_Axe
            // 
            this.radioBtn_Nul_Axe.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_Nul_Axe.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_Nul_Axe.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_Nul_Axe.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_Nul_Axe.FlatAppearance.BorderSize = 0;
            this.radioBtn_Nul_Axe.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_Nul_Axe.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_Nul_Axe.ImageAlign = System.Drawing.ContentAlignment.TopRight;
            this.radioBtn_Nul_Axe.Location = new System.Drawing.Point(522, 120);
            this.radioBtn_Nul_Axe.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_Nul_Axe.Name = "radioBtn_Nul_Axe";
            this.radioBtn_Nul_Axe.Size = new System.Drawing.Size(47, 38);
            this.radioBtn_Nul_Axe.TabIndex = 164;
            this.radioBtn_Nul_Axe.TabStop = true;
            this.radioBtn_Nul_Axe.Tag = "Btn_Null";
            this.radioBtn_Nul_Axe.Text = "Null Btn";
            this.radioBtn_Nul_Axe.UseMnemonic = false;
            this.radioBtn_Nul_Axe.UseVisualStyleBackColor = false;
            this.radioBtn_Nul_Axe.Visible = false;
            // 
            // grpTraveler
            // 
            this.grpTraveler.Controls.Add(this.radioBtn_7_Trav);
            this.grpTraveler.Controls.Add(this.radioBtn_6_Trav);
            this.grpTraveler.Controls.Add(this.radioBtn_5_Trav);
            this.grpTraveler.Controls.Add(this.radioBtn_4_Trav);
            this.grpTraveler.Controls.Add(this.radioBtn_3_Trav);
            this.grpTraveler.Controls.Add(this.radioBtn_2_Trav);
            this.grpTraveler.Controls.Add(this.radioBtn_1_Trav);
            this.grpTraveler.Controls.Add(this.radioBtn_Nul_Trav);
            this.grpTraveler.Controls.Add(this.radioBtn_0_Trav);
            this.grpTraveler.Controls.Add(this.pictureBox1);
            this.grpTraveler.Location = new System.Drawing.Point(8, 4);
            this.grpTraveler.Name = "grpTraveler";
            this.grpTraveler.Size = new System.Drawing.Size(309, 289);
            this.grpTraveler.TabIndex = 165;
            this.grpTraveler.TabStop = false;
            // 
            // radioBtn_7_Trav
            // 
            this.radioBtn_7_Trav.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_7_Trav.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_7_Trav.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_7_Trav.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_7_Trav.FlatAppearance.BorderSize = 0;
            this.radioBtn_7_Trav.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_7_Trav.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_7_Trav.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_7_Trav.ImageList = this.PilotImageList;
            this.radioBtn_7_Trav.Location = new System.Drawing.Point(83, 24);
            this.radioBtn_7_Trav.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_7_Trav.Name = "radioBtn_7_Trav";
            this.radioBtn_7_Trav.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_7_Trav.TabIndex = 163;
            this.radioBtn_7_Trav.TabStop = true;
            this.radioBtn_7_Trav.Tag = "Btn_7";
            this.radioBtn_7_Trav.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_7_Trav.UseMnemonic = false;
            this.radioBtn_7_Trav.UseVisualStyleBackColor = false;
            this.radioBtn_7_Trav.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_6_Trav
            // 
            this.radioBtn_6_Trav.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_6_Trav.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_6_Trav.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_6_Trav.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_6_Trav.FlatAppearance.BorderSize = 0;
            this.radioBtn_6_Trav.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_6_Trav.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_6_Trav.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_6_Trav.ImageList = this.PilotImageList;
            this.radioBtn_6_Trav.Location = new System.Drawing.Point(21, 96);
            this.radioBtn_6_Trav.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_6_Trav.Name = "radioBtn_6_Trav";
            this.radioBtn_6_Trav.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_6_Trav.TabIndex = 162;
            this.radioBtn_6_Trav.TabStop = true;
            this.radioBtn_6_Trav.Tag = "Btn_6";
            this.radioBtn_6_Trav.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_6_Trav.UseMnemonic = false;
            this.radioBtn_6_Trav.UseVisualStyleBackColor = false;
            this.radioBtn_6_Trav.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_5_Trav
            // 
            this.radioBtn_5_Trav.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_5_Trav.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_5_Trav.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_5_Trav.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_5_Trav.FlatAppearance.BorderSize = 0;
            this.radioBtn_5_Trav.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_5_Trav.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_5_Trav.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_5_Trav.ImageList = this.PilotImageList;
            this.radioBtn_5_Trav.Location = new System.Drawing.Point(14, 220);
            this.radioBtn_5_Trav.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_5_Trav.Name = "radioBtn_5_Trav";
            this.radioBtn_5_Trav.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_5_Trav.TabIndex = 161;
            this.radioBtn_5_Trav.TabStop = true;
            this.radioBtn_5_Trav.Tag = "Btn_5";
            this.radioBtn_5_Trav.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_5_Trav.UseMnemonic = false;
            this.radioBtn_5_Trav.UseVisualStyleBackColor = false;
            this.radioBtn_5_Trav.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_4_Trav
            // 
            this.radioBtn_4_Trav.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_4_Trav.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_4_Trav.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_4_Trav.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_4_Trav.FlatAppearance.BorderSize = 0;
            this.radioBtn_4_Trav.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_4_Trav.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_4_Trav.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_4_Trav.ImageList = this.PilotImageList;
            this.radioBtn_4_Trav.Location = new System.Drawing.Point(100, 250);
            this.radioBtn_4_Trav.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_4_Trav.Name = "radioBtn_4_Trav";
            this.radioBtn_4_Trav.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_4_Trav.TabIndex = 160;
            this.radioBtn_4_Trav.TabStop = true;
            this.radioBtn_4_Trav.Tag = "Btn_4";
            this.radioBtn_4_Trav.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_4_Trav.UseMnemonic = false;
            this.radioBtn_4_Trav.UseVisualStyleBackColor = false;
            this.radioBtn_4_Trav.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_3_Trav
            // 
            this.radioBtn_3_Trav.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_3_Trav.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_3_Trav.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_3_Trav.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_3_Trav.FlatAppearance.BorderSize = 0;
            this.radioBtn_3_Trav.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_3_Trav.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_3_Trav.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_3_Trav.ImageList = this.PilotImageList;
            this.radioBtn_3_Trav.Location = new System.Drawing.Point(187, 250);
            this.radioBtn_3_Trav.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_3_Trav.Name = "radioBtn_3_Trav";
            this.radioBtn_3_Trav.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_3_Trav.TabIndex = 159;
            this.radioBtn_3_Trav.TabStop = true;
            this.radioBtn_3_Trav.Tag = "Btn_3";
            this.radioBtn_3_Trav.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_3_Trav.UseMnemonic = false;
            this.radioBtn_3_Trav.UseVisualStyleBackColor = false;
            this.radioBtn_3_Trav.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_2_Trav
            // 
            this.radioBtn_2_Trav.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_2_Trav.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_2_Trav.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_2_Trav.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_2_Trav.FlatAppearance.BorderSize = 0;
            this.radioBtn_2_Trav.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_2_Trav.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_2_Trav.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_2_Trav.ImageList = this.PilotImageList;
            this.radioBtn_2_Trav.Location = new System.Drawing.Point(260, 220);
            this.radioBtn_2_Trav.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_2_Trav.Name = "radioBtn_2_Trav";
            this.radioBtn_2_Trav.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_2_Trav.TabIndex = 158;
            this.radioBtn_2_Trav.TabStop = true;
            this.radioBtn_2_Trav.Tag = "Btn_2";
            this.radioBtn_2_Trav.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_2_Trav.UseMnemonic = false;
            this.radioBtn_2_Trav.UseVisualStyleBackColor = false;
            this.radioBtn_2_Trav.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_1_Trav
            // 
            this.radioBtn_1_Trav.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_1_Trav.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_1_Trav.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_1_Trav.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_1_Trav.FlatAppearance.BorderSize = 0;
            this.radioBtn_1_Trav.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_1_Trav.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_1_Trav.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_1_Trav.ImageList = this.PilotImageList;
            this.radioBtn_1_Trav.Location = new System.Drawing.Point(267, 96);
            this.radioBtn_1_Trav.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_1_Trav.Name = "radioBtn_1_Trav";
            this.radioBtn_1_Trav.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_1_Trav.TabIndex = 157;
            this.radioBtn_1_Trav.TabStop = true;
            this.radioBtn_1_Trav.Tag = "Btn_1";
            this.radioBtn_1_Trav.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_1_Trav.UseMnemonic = false;
            this.radioBtn_1_Trav.UseVisualStyleBackColor = false;
            this.radioBtn_1_Trav.Click += new System.EventHandler(this.radio_Click);
            // 
            // radioBtn_Nul_Trav
            // 
            this.radioBtn_Nul_Trav.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_Nul_Trav.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_Nul_Trav.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_Nul_Trav.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_Nul_Trav.FlatAppearance.BorderSize = 0;
            this.radioBtn_Nul_Trav.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_Nul_Trav.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_Nul_Trav.ImageAlign = System.Drawing.ContentAlignment.TopRight;
            this.radioBtn_Nul_Trav.Location = new System.Drawing.Point(131, 125);
            this.radioBtn_Nul_Trav.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_Nul_Trav.Name = "radioBtn_Nul_Trav";
            this.radioBtn_Nul_Trav.Size = new System.Drawing.Size(47, 38);
            this.radioBtn_Nul_Trav.TabIndex = 156;
            this.radioBtn_Nul_Trav.TabStop = true;
            this.radioBtn_Nul_Trav.Tag = "Btn_Null";
            this.radioBtn_Nul_Trav.Text = "Null Btn";
            this.radioBtn_Nul_Trav.UseMnemonic = false;
            this.radioBtn_Nul_Trav.UseVisualStyleBackColor = false;
            this.radioBtn_Nul_Trav.Visible = false;
            // 
            // radioBtn_0_Trav
            // 
            this.radioBtn_0_Trav.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioBtn_0_Trav.BackColor = System.Drawing.Color.Transparent;
            this.radioBtn_0_Trav.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_0_Trav.FlatAppearance.BorderColor = System.Drawing.Color.Black;
            this.radioBtn_0_Trav.FlatAppearance.BorderSize = 0;
            this.radioBtn_0_Trav.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
            this.radioBtn_0_Trav.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.radioBtn_0_Trav.ImageKey = "Btn_Pilot Off.jpg";
            this.radioBtn_0_Trav.ImageList = this.PilotImageList;
            this.radioBtn_0_Trav.Location = new System.Drawing.Point(203, 25);
            this.radioBtn_0_Trav.Margin = new System.Windows.Forms.Padding(0);
            this.radioBtn_0_Trav.Name = "radioBtn_0_Trav";
            this.radioBtn_0_Trav.Size = new System.Drawing.Size(30, 30);
            this.radioBtn_0_Trav.TabIndex = 153;
            this.radioBtn_0_Trav.TabStop = true;
            this.radioBtn_0_Trav.Tag = "Btn_0";
            this.radioBtn_0_Trav.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.radioBtn_0_Trav.UseMnemonic = false;
            this.radioBtn_0_Trav.UseVisualStyleBackColor = false;
            this.radioBtn_0_Trav.Click += new System.EventHandler(this.radio_Click);
            // 
            // pictureBox1
            // 
            this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
            this.pictureBox1.Location = new System.Drawing.Point(26, 50);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(254, 191);
            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.pictureBox1.TabIndex = 0;
            this.pictureBox1.TabStop = false;
            // 
            // RBC9SpaceNav
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.Color.White;
            this.ClientSize = new System.Drawing.Size(945, 713);
            this.ControlBox = false;
            this.Controls.Add(this.radioBtn_Nul_Axe);
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.tabControl1);
            this.Controls.Add(this.lbl_rZ);
            this.Controls.Add(this.lbl_rY);
            this.Controls.Add(this.lbl_rX);
            this.Controls.Add(this.grpTraveler);
            this.Controls.Add(this.lbl_Z);
            this.Controls.Add(this.btnCalib);
            this.Controls.Add(this.btnApply);
            this.Controls.Add(this.lbl_Y);
            this.Controls.Add(this.lbl_X);
            this.Controls.Add(this.radioAxe_4);
            this.Controls.Add(this.btnCancel);
            this.Controls.Add(this.radioAxe_3);
            this.Controls.Add(this.radioAxe_5);
            this.Controls.Add(this.radioAxe_1);
            this.Controls.Add(this.radioAxe_0);
            this.Controls.Add(this.radioAxe_2);
            this.Controls.Add(this.grpPilot);
            this.Controls.Add(this.grpSpaceNav);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "RBC9SpaceNav";
            this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
            this.Text = "RBC9 - SpaceNavigator";
            this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.RBC9SpaceNav_FormClosed);
            this.Load += new System.EventHandler(this.RBC9_Load);
            ((System.ComponentModel.ISupportInitialize)(this.pictureRight)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureLeft)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.gridLayout)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.layoutStructBindingSource)).EndInit();
            this.grpDeadZone.ResumeLayout(false);
            this.grpDeadZone.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.trkDeadZone)).EndInit();
            this.grpSpaceNavAxe.ResumeLayout(false);
            this.grpSpaceNavAxe.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.layoutBindBindingSource)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.trkAxeZone)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.trkMaxVal)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.trkMinVal)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.AxePartBindingSource)).EndInit();
            this.grpSpaceNavBtn.ResumeLayout(false);
            this.grpSpaceNavBtn.PerformLayout();
            this.grpTypeDelay.ResumeLayout(false);
            this.grpTypeDelay.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.trkTypeDelay)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.PressTypeBindingSource)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.BindToBindingSource)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.JoyAxeBindingSource)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.JoyPOVBindingSource)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.JoyBtnBindingSource)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.MouBtnBindingSource)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.trkMouSensi)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.trkRepeat)).EndInit();
            this.grpLayout.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.ProfilLstBindingSource)).EndInit();
            this.grpMouBtn.ResumeLayout(false);
            this.grpJoyBtn.ResumeLayout(false);
            this.grpJoyPov.ResumeLayout(false);
            this.grpJoyAxe.ResumeLayout(false);
            this.grpMouseSensi.ResumeLayout(false);
            this.grpMouseSensi.PerformLayout();
            this.grpKey.ResumeLayout(false);
            this.grpKey.PerformLayout();
            this.grpWWW.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.WWWBindingSource)).EndInit();
            this.grpBindType.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.DefaultLayoutBindingSource)).EndInit();
            this.grpDefault.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.pictureSpaceNav)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.gridAppAuto)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.layoutAppAutoBindingSource)).EndInit();
            this.tabControl1.ResumeLayout(false);
            this.tabPage1.ResumeLayout(false);
            this.grpComment.ResumeLayout(false);
            this.grpComment.PerformLayout();
            this.grpTypePress.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.gridBindTo)).EndInit();
            this.tabPage2.ResumeLayout(false);
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.groupBox2.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.DeviceBindingSource)).EndInit();
            this.MenuBind.ResumeLayout(false);
            this.MenuLayout.ResumeLayout(false);
            this.grpSpaceNav.ResumeLayout(false);
            this.grpSpaceNav.PerformLayout();
            this.grpPilot.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.picturePilot)).EndInit();
            this.grpTraveler.ResumeLayout(false);
            this.grpTraveler.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.PictureBox pictureRight;
        private System.Windows.Forms.PictureBox pictureLeft;
        private System.Windows.Forms.Label lbl_rZ;
        private System.Windows.Forms.Label lbl_rY;
        private System.Windows.Forms.Label lbl_rX;
        private System.Windows.Forms.Label lbl_Z;
        private System.Windows.Forms.Label lbl_Y;
        private System.Windows.Forms.Label lbl_X;
        private System.Windows.Forms.DataGridView gridLayout;
        private System.Windows.Forms.BindingSource layoutStructBindingSource;
        private System.Windows.Forms.GroupBox grpDeadZone;
        private System.Windows.Forms.TextBox txtDeadZone;
        private System.Windows.Forms.TrackBar trkDeadZone;
        private System.Windows.Forms.BindingSource layoutBindBindingSource;
        private System.Windows.Forms.BindingSource BindToBindingSource;
        private System.Windows.Forms.BindingSource AxePartBindingSource;
        private System.Windows.Forms.GroupBox grpSpaceNavAxe;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label lblMax;
        private System.Windows.Forms.Label lblMin;
        private System.Windows.Forms.TrackBar trkMaxVal;
        private System.Windows.Forms.TrackBar trkMinVal;
        private System.Windows.Forms.ComboBox cboAxePart;
        private System.Windows.Forms.CheckBox chkInvert;
        private System.Windows.Forms.GroupBox grpSpaceNavBtn;
        private System.Windows.Forms.CheckBox chkInvertBtn;
        private System.Windows.Forms.ComboBox cboBintTo;
        private System.Windows.Forms.ComboBox cboJoyAxe;
        private System.Windows.Forms.BindingSource JoyAxeBindingSource;
        private System.Windows.Forms.ComboBox cboJoyPOV;
        private System.Windows.Forms.BindingSource JoyPOVBindingSource;
        private System.Windows.Forms.ComboBox cboJoyBtn;
        private System.Windows.Forms.BindingSource JoyBtnBindingSource;
        private System.Windows.Forms.ComboBox cboMouBtn;
        private System.Windows.Forms.BindingSource MouBtnBindingSource;
        private System.Windows.Forms.TrackBar trkMouSensi;
        private System.Windows.Forms.Label lblValSensi;
        private System.Windows.Forms.Label lblMouSensi;
        private System.Windows.Forms.Label lblMouSensiTaux;
        private System.Windows.Forms.BindingSource ProfilLstBindingSource;
        private System.Windows.Forms.ComboBox cboKey1;
        private System.Windows.Forms.ComboBox cboKey2;
        private System.Windows.Forms.ComboBox cboKey5;
        private System.Windows.Forms.ComboBox cboKey3;
        private System.Windows.Forms.ComboBox cboKey4;
        private System.Windows.Forms.ComboBox cboKey;
        private System.Windows.Forms.CheckBox chkRepeat;
        private System.Windows.Forms.TrackBar trkRepeat;
        private System.Windows.Forms.Label lblRepeatDelay;
        private System.Windows.Forms.GroupBox grpLayout;
        private System.Windows.Forms.ComboBox cboProfil;
        private System.Windows.Forms.GroupBox grpKey;
        private System.Windows.Forms.GroupBox grpJoyAxe;
        private System.Windows.Forms.GroupBox grpJoyBtn;
        private System.Windows.Forms.GroupBox grpJoyPov;
        private System.Windows.Forms.GroupBox grpMouBtn;
        private System.Windows.Forms.GroupBox grpMouseSensi;
        private System.Windows.Forms.GroupBox grpBindType;
        private System.Windows.Forms.ComboBox cboDefault;
        private System.Windows.Forms.BindingSource DefaultLayoutBindingSource;
        private System.Windows.Forms.GroupBox grpDefault;
        private System.Windows.Forms.PictureBox pictureSpaceNav;
        private System.Windows.Forms.RadioButton radioAxe_1;
        private System.Windows.Forms.RadioButton radioAxe_0;
        private System.Windows.Forms.RadioButton radioAxe_2;
        private System.Windows.Forms.RadioButton radioAxe_4;
        private System.Windows.Forms.RadioButton radioAxe_3;
        private System.Windows.Forms.RadioButton radioAxe_5;
        private System.Windows.Forms.RadioButton radioBtn_1_Nav;
        private System.Windows.Forms.RadioButton radioBtn_0_Nav;
        private System.Windows.Forms.Button btnApply;
        private System.Windows.Forms.Button btnCancel;
        private System.Windows.Forms.BindingSource layoutAppAutoBindingSource;
        private System.Windows.Forms.DataGridView gridAppAuto;
        private System.Windows.Forms.TabControl tabControl1;
        private System.Windows.Forms.TabPage tabPage1;
        private System.Windows.Forms.TabPage tabPage2;
        private System.Windows.Forms.Button btnDelAppAuto;
        private System.Windows.Forms.Button btnAddAppAuto;
        private System.Windows.Forms.CheckBox chkAutoApp;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.DataGridView gridBindTo;
        private System.Windows.Forms.DataGridViewTextBoxColumn txtDataGridViewTextBoxColumn;
        private System.Windows.Forms.Button btnCalib;
        private System.Windows.Forms.Label lblAxeDead;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.TrackBar trkAxeZone;
        private System.Windows.Forms.ContextMenuStrip MenuBind;
        private System.Windows.Forms.ToolStripMenuItem MenuBindAdd;
        private System.Windows.Forms.ToolStripMenuItem MenuBindDel;
        private System.Windows.Forms.ToolStripSeparator MenuBindSeparator;
        private System.Windows.Forms.ToolStripMenuItem MenuBindCopy;
        private System.Windows.Forms.ToolStripMenuItem MenuBindPaste;
        private System.Windows.Forms.ContextMenuStrip MenuLayout;
        private System.Windows.Forms.ToolStripMenuItem MenuLayoutAdd;
        private System.Windows.Forms.ToolStripMenuItem MenuLayoutDel;
        private System.Windows.Forms.ToolStripSeparator MenuLayoutSeparator;
        private System.Windows.Forms.ToolStripMenuItem MenuLayoutDuplicate;
        private System.Windows.Forms.GroupBox grpWWW;
        private System.Windows.Forms.ComboBox cboWWW;
        private System.Windows.Forms.BindingSource WWWBindingSource;
        private System.Windows.Forms.ToolStripMenuItem MenuLayoutExport;
        private System.Windows.Forms.OpenFileDialog openFileBind;
        private System.Windows.Forms.SaveFileDialog saveFileBind;
        private System.Windows.Forms.ToolStripMenuItem MenuLayoutImport;
        private System.Windows.Forms.CheckBox chkInfoBulle;
        private System.Windows.Forms.DataGridViewTextBoxColumn profilNameDataGridViewTextBoxColumn;
        private System.Windows.Forms.CheckBox chkIcon;
        private System.Windows.Forms.ComboBox cboPressType;
        private System.Windows.Forms.BindingSource PressTypeBindingSource;
        private System.Windows.Forms.TrackBar trkTypeDelay;
        private System.Windows.Forms.Label lblTypeDelay;
        private System.Windows.Forms.GroupBox grpTypeDelay;
        private System.Windows.Forms.GroupBox grpTypePress;
        private System.Windows.Forms.TextBox txtComment;
        private System.Windows.Forms.DataGridViewTextBoxColumn bindToTxtDataGridViewTextBoxColumn1;
        private System.Windows.Forms.DataGridViewTextBoxColumn Comment;
        private System.Windows.Forms.GroupBox grpComment;
        private System.Windows.Forms.GroupBox groupBox2;
        private System.Windows.Forms.BindingSource DeviceBindingSource;
        private System.Windows.Forms.ComboBox cboDevice;
        private System.Windows.Forms.GroupBox grpSpaceNav;
        private System.Windows.Forms.GroupBox grpPilot;
        private System.Windows.Forms.PictureBox picturePilot;
        private System.Windows.Forms.RadioButton radioBtn_Nul_Nav;
        private System.Windows.Forms.RadioButton radioBtn_Nul_Pil;
        private System.Windows.Forms.RadioButton radioBtn_Nul_Axe;
        private System.Windows.Forms.RadioButton radioBtn_0_Pil;
        private System.Windows.Forms.ImageList PilotImageList;
        private System.Windows.Forms.RadioButton radioBtn_9_Pil;
        private System.Windows.Forms.RadioButton radioBtn_8_Pil;
        private System.Windows.Forms.RadioButton radioBtn_7_Pil;
        private System.Windows.Forms.RadioButton radioBtn_6_Pil;
        private System.Windows.Forms.RadioButton radioBtn_5_Pil;
        private System.Windows.Forms.RadioButton radioBtn_4_Pil;
        private System.Windows.Forms.RadioButton radioBtn_3_Pil;
        private System.Windows.Forms.RadioButton radioBtn_2_Pil;
        private System.Windows.Forms.RadioButton radioBtn_1_Pil;
        private System.Windows.Forms.RadioButton radioBtn_19_Pil;
        private System.Windows.Forms.RadioButton radioBtn_18_Pil;
        private System.Windows.Forms.RadioButton radioBtn_17_Pil;
        private System.Windows.Forms.RadioButton radioBtn_16_Pil;
        private System.Windows.Forms.RadioButton radioBtn_15_Pil;
        private System.Windows.Forms.RadioButton radioBtn_14_Pil;
        private System.Windows.Forms.RadioButton radioBtn_13_Pil;
        private System.Windows.Forms.RadioButton radioBtn_12_Pil;
        private System.Windows.Forms.RadioButton radioBtn_11_Pil;
        private System.Windows.Forms.RadioButton radioBtn_10_Pil;
        private System.Windows.Forms.RadioButton radioBtn_20_Pil;
        private System.Windows.Forms.GroupBox grpTraveler;
        private System.Windows.Forms.RadioButton radioBtn_7_Trav;
        private System.Windows.Forms.RadioButton radioBtn_6_Trav;
        private System.Windows.Forms.RadioButton radioBtn_5_Trav;
        private System.Windows.Forms.RadioButton radioBtn_4_Trav;
        private System.Windows.Forms.RadioButton radioBtn_3_Trav;
        private System.Windows.Forms.RadioButton radioBtn_2_Trav;
        private System.Windows.Forms.RadioButton radioBtn_1_Trav;
        private System.Windows.Forms.RadioButton radioBtn_Nul_Trav;
        private System.Windows.Forms.RadioButton radioBtn_0_Trav;
        private System.Windows.Forms.PictureBox pictureBox1;

    }
}

using System;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;

namespace USB_HID
{
	#region Custom exception
	/// <summary>
	/// Generic HID device exception
	/// </summary>
    public class HIDDeviceException : ApplicationException
    {
        public HIDDeviceException(string strMessage) : base(strMessage) { }

        public static HIDDeviceException GenerateWithWinError(string strMessage)
        {
            return new HIDDeviceException(string.Format("Msg:{0} WinEr:{1:X8}", strMessage, Marshal.GetLastWin32Error()));
        }
    }
	#endregion

    public class HIDBtn
    {
        private bool _State_Current;
        public bool State_Current
        {
            get
            {
                return _State_Current;
            }

            set
            {
               
                State_Prev = _State_Current;
               _State_Current = value;
               State_Changed = (_State_Current != State_Prev);
            }
        }

        public bool State_Prev;
        public bool State_Changed;
    }

    public class HIDAxe
    {
        private short _State_Current;
        public short State_Current
        {
            get
            {
                return _State_Current;
            }

            set
            {
                
                State_Prev = _State_Current;
                _State_Current = value;
                State_Changed = (_State_Current != State_Prev);
            }
        }

        public short State_Prev;
        public bool State_Changed;
    }


    public abstract class HIDStates
    {
        public int NbBtn;
        public int  NbAxe;

        public HIDBtn[] Btn;
        public HIDAxe[] Axe;
        public short ProfilNum;
        public bool IsRBC9Present;

        public void HitInit()
        {
            int i;
            Btn = new HIDBtn[NbBtn];
            Axe = new HIDAxe[NbAxe];

            for (i = 0; i < NbBtn; Btn[i++] = new HIDBtn());
            for (i = 0; i < NbAxe; Axe[i++] = new HIDAxe()) ;

            IsRBC9Present = false;
        }

        public void HitInit(int vNbBtn, int vNbAxe)
        {
            NbBtn = vNbBtn;
            NbAxe = vNbAxe;
            HitInit();
        }
       
    }

	/// <summary>
	/// Abstract HID device : Derive your new device controller class from this
	/// </summary>
    public abstract class HIDDevice : Win32Usb, IDisposable
    {
		#region Privates variables
		/// <summary>Filestream we can use to read/write from</summary>
        private FileStream m_oFile;
		/// <summary>Length of input report : device gives us this</summary>
		private int m_nInputReportLength;
		/// <summary>Length if output report : device gives us this</summary>
		private int m_nOutputReportLength;
		/// <summary>Handle to the device</summary>
		private IntPtr m_hHandle;

		#endregion

        #region Public variables
        public int nVid;
        public int nPid;

        #endregion

        #region IDisposable Members
        /// <summary>
		/// Dispose method
		/// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
		/// <summary>
		/// Disposer called by both dispose and finalise
		/// </summary>
		/// <param name="bDisposing">True if disposing</param>
        protected virtual void Dispose(bool bDisposing)
        {
            if (bDisposing)	// if we are disposing, need to close the managed resources
            {
                if (m_oFile != null)
                {
                    m_oFile.Close();
                    m_oFile = null;
                }
            }
            if (m_hHandle != IntPtr.Zero)	// Dispose and finalize, get rid of unmanaged resources
            {
                CloseHandle(m_hHandle);
            }
        }
        #endregion

		#region Privates/protected
		/// <summary>
		/// Initialises the device
		/// </summary>
		/// <param name="strPath">Path to the device</param>
		private void Initialise(string strPath)
		{
			// Create the file from the device path
            m_hHandle = CreateFile(strPath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, IntPtr.Zero);
			if ( m_hHandle != InvalidHandleValue )	// if the open worked...
			{
				IntPtr lpData;
				if (HidD_GetPreparsedData(m_hHandle, out lpData))	// get windows to read the device data into an internal buffer
				{
                    try
                    {
                        HidCaps oCaps;
                        HidP_GetCaps(lpData, out oCaps);	// extract the device capabilities from the internal buffer
                        m_nInputReportLength = oCaps.InputReportByteLength;	// get the input...
                        m_nOutputReportLength = oCaps.OutputReportByteLength;	// ... and output report lengths
                        m_oFile = new FileStream(m_hHandle, FileAccess.Read | FileAccess.Write, true, m_nInputReportLength, true);	// wrap the file handle in a .Net file stream
                        BeginAsyncRead();	// kick off the first asynchronous read
                    }
                    catch
                    {
                        Console.WriteLine("Erreur 55");
                    }
					finally
					{
                       
						HidD_FreePreparsedData(ref lpData);	// before we quit the funtion, we must free the internal buffer reserved in GetPreparsedData
					}
				}
				else	// GetPreparsedData failed? Chuck an exception
				{
					throw HIDDeviceException.GenerateWithWinError("GetPreparsedData failed");
				}
			}
			else	// File open failed? Chuck an exception
			{
				m_hHandle = IntPtr.Zero;
				throw HIDDeviceException.GenerateWithWinError("Failed to create device file");
			}
		}
		/// <summary>
		/// Kicks off an asynchronous read which completes when data is read or when the device
		/// is disconnected. Uses a callback.
		/// </summary>
        private void BeginAsyncRead()
        {
            byte[] arrInputReport = new byte[m_nInputReportLength];
			// put the buff we used to receive the stuff as the async state then we can get at it when the read completes
     
            m_oFile.BeginRead(arrInputReport, 0, m_nInputReportLength, new AsyncCallback(ReadCompleted), arrInputReport);
    

        }
		/// <summary>
		/// Callback for above. Care with this as it will be called on the background thread from the async read
		/// </summary>
		/// <param name="iResult">Async result parameter</param>
        protected void ReadCompleted(IAsyncResult iResult)
        {
            byte[] arrBuff = (byte[])iResult.AsyncState;	// retrieve the read buffer
            try
            {
   
                m_oFile.EndRead(iResult);	// call end read : this throws any exceptions that happened during the read
 
                try
                {
					InputReport oInRep = CreateInputReport();	// Create the input report for the device
					oInRep.SetData(arrBuff);	// and set the data portion - this processes the data received into a more easily understood format depending upon the report type
                    HandleDataReceived(oInRep);	// pass the new input report on to the higher level handler
                }
                finally
                {
                  //  Console.WriteLine("Erreur 2");
       
                    BeginAsyncRead();	// when all that is done, kick off another read for the next report

                }                
            }
            catch(IOException )	// if we got an IO exception, the device was removed
            {
                Console.WriteLine("Erreur 1");
                HandleDeviceRemoved();
                Dispose();
            }
        }
		/// <summary>
		/// Write an output report to the device.
		/// </summary>
		/// <param name="oOutRep">Output report to write</param>
        protected void Write(OutputReport oOutRep)
        {
           	try
			{
				//m_oFile.Write(oOutRep.Buffer, 0, oOutRep.BufferLength);
                unsafe
                {
                 
                    bool Success = HidD_SetOutputReport(m_hHandle, ref oOutRep.Buffer[0], oOutRep.BufferLength);
                }
                
			}
                
			catch(IOException )
           // catch (Exception ex)
			{
                Console.WriteLine("Erreur 3");
				// The device was removed!
				throw new HIDDeviceException("Device was removed");
			}
        }
		/// <summary>
		/// virtual handler for any action to be taken when data is received. Override to use.
		/// </summary>
		/// <param name="oInRep">The input report that was received</param>
		protected virtual void HandleDataReceived(InputReport oInRep)
		{
		}
		/// <summary>
		/// Virtual handler for any action to be taken when a device is removed. Override to use.
		/// </summary>
		protected virtual void HandleDeviceRemoved()
		{
          
		}
		/// <summary>
		/// Helper method to return the device path given a DeviceInterfaceData structure and an InfoSet handle.
		/// Used in 'FindDevice' so check that method out to see how to get an InfoSet handle and a DeviceInterfaceData.
		/// </summary>
		/// <param name="hInfoSet">Handle to the InfoSet</param>
		/// <param name="oInterface">DeviceInterfaceData structure</param>
		/// <returns>The device path or null if there was some problem</returns>
        private static string GetDevicePath(IntPtr hInfoSet, ref SP_DEVICE_INTERFACE_DATA oInterface)
		{
			int nRequiredSize = 0;
			// Get the device interface details
            SP_DEVINFO_DATA odevData = new SP_DEVINFO_DATA();

            if (!SetupDiGetDeviceInterfaceDetail(hInfoSet, oInterface, IntPtr.Zero, 0, ref nRequiredSize, odevData))
			{
                IntPtr buffer = Marshal.AllocHGlobal(nRequiredSize);
                SP_DEVICE_INTERFACE_DETAIL_DATA oDetail = new SP_DEVICE_INTERFACE_DETAIL_DATA();
                oDetail.cbSize = Marshal.SizeOf(typeof(SP_DEVICE_INTERFACE_DETAIL_DATA));
                Marshal.StructureToPtr(oDetail, buffer, false);
                if (!SetupDiGetDeviceInterfaceDetail(hInfoSet, oInterface, buffer, nRequiredSize, ref nRequiredSize, odevData))
                {
                    Marshal.FreeHGlobal(buffer);
                    return null;
                }

                IntPtr pDevicePath = (IntPtr)((int)buffer + Marshal.SizeOf(typeof(int)));
                string devicePath = Marshal.PtrToStringAuto(pDevicePath);
                Marshal.FreeHGlobal(buffer);

                return devicePath;

			}
			return null;
		}

        private static short GetDeviceUsage(string strPath)
        {
            IntPtr m_hHandle;
            short vUsage = -1;

            // Create the file from the device path
            m_hHandle = CreateFile(strPath, 0, FILE_SHARE_READ | FILE_SHARE_WRITE , IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
            if (m_hHandle != InvalidHandleValue)	// if the open worked...
            {
                IntPtr lpData;
                if (HidD_GetPreparsedData(m_hHandle, out lpData))	// get windows to read the device data into an internal buffer
                {
                    try
                    {
                        HidCaps oCaps;
                        HidP_GetCaps(lpData, out oCaps);	// extract the device capabilities from the internal buffer
                        vUsage = oCaps.Usage;
                    }
                    catch
                    {
                        Console.WriteLine("Erreur 55");
                    }
                    finally
                    {

                        HidD_FreePreparsedData(ref lpData);	// before we quit the funtion, we must free the internal buffer reserved in GetPreparsedData
                    }
                }
                else	// GetPreparsedData failed? Chuck an exception
                {
                    throw HIDDeviceException.GenerateWithWinError("GetPreparsedData failed");
                }

                CloseHandle(m_hHandle);
                m_hHandle = IntPtr.Zero;
            }
            else	// File open failed? Chuck an exception
            {
                m_hHandle = IntPtr.Zero;
                throw HIDDeviceException.GenerateWithWinError("Failed to create device file");
            }

            return vUsage;
        }

        static bool StateChange(IntPtr hDevInfo, int SelectedItem, int NewState)
        {

            SP_PROPCHANGE_PARAMS PropChangeParams;

            SP_DEVINFO_DATA2 DeviceInfoData;

            PropChangeParams = new SP_PROPCHANGE_PARAMS();

            PropChangeParams.Init();

            DeviceInfoData = new SP_DEVINFO_DATA2();

            PropChangeParams.ClassInstallHeader.cbSize = Marshal.SizeOf(PropChangeParams.ClassInstallHeader);

            DeviceInfoData.cbSize = Marshal.SizeOf(DeviceInfoData);

            if (!SetupDiEnumDeviceInfo(hDevInfo, SelectedItem, ref DeviceInfoData))
                return false;

            PropChangeParams.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE;
            PropChangeParams.Scope = DICS_FLAG_GLOBAL;
            PropChangeParams.StateChange = NewState;

            if (!SetupDiSetClassInstallParams(hDevInfo,
                ref DeviceInfoData,
                ref PropChangeParams.ClassInstallHeader,
                Marshal.SizeOf(PropChangeParams)))
                return false;

            if (!SetupDiCallClassInstaller(Win32Usb.DIF_PROPERTYCHANGE, hDevInfo, ref DeviceInfoData))
                return false;

            return true;
        }
  
/*  exemple restrat driver ??
        BOOLEAN CSetupDIMgr::RestartDevice(void) 
{ 
    CString sHardwareID; 
    if(HardwareID(sHardwareID)) 
    { 
        do 
        { 
            SP_PROPCHANGE_PARAMS params; 

            // for future compatibility; this will zero out the entire struct, rather 
            // than just the fields which exist now 
            memset(&params, 0, sizeof(SP_PROPCHANGE_PARAMS)); 

            // initialize the SP_CLASSINSTALL_HEADER struct at the beginning of the 
            // SP_PROPCHANGE_PARAMS struct, so that SetupDiSetClassInstallParams will 
            // work 
            params.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER); 

            params.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE; 
          
             // initialize SP_PROPCHANGE_PARAMS such that the device will be stopped. 
            params.StateChange = DICS_PROPCHANGE; 
            params.Scope       = DICS_FLAG_CONFIGSPECIFIC; 
            params.HwProfile   = 0; // current profile 

            if(!SetupDiSetClassInstallParams(m_devInfo, &m_devInfoData, 
                (PSP_CLASSINSTALL_HEADER) &params, 
                sizeof(SP_PROPCHANGE_PARAMS))) 
            { 
                TRACE("in RestartDevice(): couldn't set the install parameters!"); 
                TRACE(" error: %u\n", GetLastError()); 
                return FALSE; 
            } 

            if(!SetupDiCallClassInstaller(DIF_PROPERTYCHANGE, m_devInfo, &m_devInfoData)) 
            { 
                  TRACE("in RestartDevice(): call to class installer (STOP) failed!"); 
                  TRACE(" error: %u\n", GetLastError() ); 
                  return FALSE; 
            } 
        } 
        while(FindHardwareID(sHardwareID, m_nDevIndex)); 
        return TRUE; 
     } 
     return FALSE; 
}*/
		#endregion

		#region Public static
		/// <summary>
		/// Finds a device given its PID and VID
		/// </summary>
		/// <param name="nVid">Vendor id for device (VID)</param>
		/// <param name="nPid">Product id for device (PID)</param>
		/// <param name="oType">Type of device class to create</param>
		/// <returns>A new device class of the given type or null</returns>
		public static HIDDevice FindDevice(int nVid, int nPid, short nUsage,Type oType)
        {
            string strPath = string.Empty;
			string strSearch = string.Format("vid_{0:x4}&pid_{1:x4}", nVid, nPid); // first, build the path search string
            Guid gHid;
            HidD_GetHidGuid(out gHid);	// next, get the GUID from Windows that it uses to represent the HID USB interface
            IntPtr hInfoSet = SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);	// this gets a list of all HID devices currently connected to the computer (InfoSet)
            try
            {
                SP_DEVICE_INTERFACE_DATA oInterface = new SP_DEVICE_INTERFACE_DATA();	// build up a device interface data block
            
                int nIndex = 0;
                while (SetupDiEnumDeviceInterfaces(hInfoSet, null, ref gHid, nIndex, oInterface))	// this gets the device interface information for a device at index 'nIndex' in the memory block
                {
                    string strDevicePath = GetDevicePath(hInfoSet, ref oInterface);	// get the device path (see helper method 'GetDevicePath')
                    if (strDevicePath.IndexOf(strSearch) >= 0)	// do a string search, if we find the VID/PID string then we found our device!
                    {

                        if (GetDeviceUsage(strDevicePath) == nUsage) 
                        {
                            HIDDevice oNewDevice = (HIDDevice)Activator.CreateInstance(oType);	// create an instance of the class for this device
                            oNewDevice.Initialise(strDevicePath);	// initialise it with the device path
                            oNewDevice.nVid =nVid;
                                oNewDevice.nPid = nPid;
                            SetupDiDestroyDeviceInfoList(hInfoSet);
                            return oNewDevice;	// and return it
                        }
                    }
                    nIndex++;	// if we get here, we didn't find our device. So move on to the next one.
                }
            }
            catch (HIDDeviceException)
            {
                Console.WriteLine("Erreur 4");
               // throw new HIDDeviceException("IO Error");

            }

            finally
            {
				// Before we go, we have to free up the InfoSet memory reserved by SetupDiGetClassDevs
                SetupDiDestroyDeviceInfoList(hInfoSet);
            }
            return null;	// oops, didn't find our device
        }


		#endregion

		#region Publics
		/// <summary>
		/// Accessor for output report length
		/// </summary>
		public int OutputReportLength
		{
			get
			{
				return m_nOutputReportLength;
			}
		}
		/// <summary>
		/// Accessor for input report length
		/// </summary>
		public int InputReportLength
		{
			get
			{
				return m_nInputReportLength;
			}
		}
		/// <summary>
		/// Virtual method to create an input report for this device. Override to use.
		/// </summary>
		/// <returns>A shiny new input report</returns>
		public virtual InputReport CreateInputReport()
		{
			return null;
		}
		#endregion
    }
}
using System;

namespace USB_HID
{
	/// <summary>
	/// Base class for report types. Simply wraps a byte buffer.
	/// </summary>
	public abstract class Report
	{
		#region Member variables
		/// <summary>Buffer for raw report bytes</summary>
		private byte[] m_arrBuffer;
		/// <summary>Length of the report</summary>
		private int m_nLength;
		#endregion

		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="oDev">Constructing device</param>
		public Report(HIDDevice oDev)
		{
			// Do nothing
		}

		/// <summary>
		/// Sets the raw byte array.
		/// </summary>
		/// <param name="arrBytes">Raw report bytes</param>
		protected void SetBuffer(byte[] arrBytes)
		{
			m_arrBuffer = arrBytes;
			m_nLength = m_arrBuffer.Length;
		}

		/// <summary>
		/// Accessor for the raw byte buffer
		/// </summary>
		public byte[] Buffer
		{
			get
			{
				return m_arrBuffer;
			}
		}
		/// <summary>
		/// Accessor for the buffer length
		/// </summary>
		public int BufferLength
		{
			get
			{
				return m_nLength;
			}
		}
	}
	/// <summary>
	/// Defines a base class for output reports. To use output reports, just put the bytes into the raw buffer.
	/// </summary>
	public abstract class OutputReport : Report
	{
		/// <summary>
		/// Construction. Setup the buffer with the correct output report length dictated by the device
		/// </summary>
		/// <param name="oDev">Creating device</param>
		public OutputReport(HIDDevice oDev) : base(oDev)
		{
			SetBuffer(new byte[oDev.OutputReportLength]);
		}
	}
	/// <summary>
	/// Defines a base class for input reports. To use input reports, use the SetData method and override the 
	/// ProcessData method.
	/// </summary>
	public abstract class InputReport : Report
	{
		/// <summary>
		/// Construction. Do nothing
		/// </summary>
		/// <param name="oDev">Creating device</param>
		public InputReport(HIDDevice oDev) : base(oDev)
		{
		}
		/// <summary>
		/// Call this to set the buffer given a raw input report. Calls an overridable method to
		/// should automatically parse the bytes into meaningul structures.
		/// </summary>
		/// <param name="arrData">Raw input report.</param>
		public void SetData(byte[] arrData)
		{
			SetBuffer(arrData);
			ProcessData();
		}
		/// <summary>
		/// Override this to process the input report into something useful
		/// </summary>
		public abstract void ProcessData();
	}
}
using System;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace USB_HID
{

    public enum OutputValue
    {
        REPORT_ID_CMD = 0xf0,
        NavReport = 0x01,
        Reload = 0x02,
        Led = 0x04,
        Init=0x06,
        Calibrate = 0x07,
        Profil = 0x08,
        Config = 0xFF
    }

    public class NavStates : HIDStates
    {
        public NavStates()
        {
            base.HitInit(21, 6);
        }

    }

    #region Event definitions

    public class HIDChangedEventArgs : EventArgs
    {

        public readonly NavStates HIDValue;
        public HIDChangedEventArgs(NavStates arrStates)
        {
            HIDValue = arrStates;
        }
    }

    public delegate void HIDChangedEventHandler(object sender, HIDChangedEventArgs args);

    #endregion

    public class SpaceNavigator : HIDDevice
    {
        #region Public attributes/methods


        public event HIDChangedEventHandler OnButtonChanged;
        public event HIDChangedEventHandler OnDeviceRemoved;

        public override InputReport CreateInputReport()
        {
            return new BuzzInputReport(this);
        }
        private NavStates CurrentHidValue;

        public void SetLed(bool bLight)
        {
            if (!CurrentHidValue.IsRBC9Present) return;

            BuzzOutputReport oRep = new BuzzOutputReport(this);
            oRep.SetOutput(OutputValue.Led, bLight);

            WriteOutput(oRep);
        }


        public void SetModeConfig(bool SendOn)
        {
            if (!CurrentHidValue.IsRBC9Present) return;

            BuzzOutputReport oRep = new BuzzOutputReport(this);
            oRep.SetOutput(OutputValue.Config, SendOn);

            WriteOutput(oRep);
        }

        public void ReloadProfil()
        {
            BuzzOutputReport oRep = new BuzzOutputReport(this);
            oRep.SetOutput(OutputValue.Reload);

            WriteOutput(oRep);
        }

        public void GetNavReport()
        {
 
            BuzzOutputReport oRep = new BuzzOutputReport(this);
            oRep.SetOutput(OutputValue.NavReport);

            WriteOutput(oRep);
        }

        public void Calibrate()
        {
            BuzzOutputReport oRep = new BuzzOutputReport(this);
            oRep.SetOutput(OutputValue.Calibrate);

            WriteOutput(oRep);
        }

        public void SelectProfil(short ProfilNum)
        {
            if (!CurrentHidValue.IsRBC9Present) return;

            BuzzOutputReport oRep = new BuzzOutputReport(this);
            oRep.SetOutput(OutputValue.Profil, ProfilNum);

            WriteOutput(oRep);
        }

        private void WriteOutput(BuzzOutputReport oRep)
        {
            try
            {
                Write(oRep); // write the output report
            }
            catch (HIDDeviceException)
            {
                Console.WriteLine("Erreur 9");
                // Device may have been removed!
            }
        }


        public SpaceNavigator()
        {

            CurrentHidValue = new NavStates();
        }

        public static SpaceNavigator FindSpaceNav(int nPid, short nUsage)
        {
            return  (SpaceNavigator)FindDevice(0x046D, nPid, nUsage, typeof(SpaceNavigator));
        }


        private void Parse_TrameHID(byte[] TrameHID)
        {

            switch (TrameHID[0])
            {
                case 1:

                    CurrentHidValue.Axe[0].State_Current = (short)(TrameHID[1] + (TrameHID[2] << 8));
                    CurrentHidValue.Axe[1].State_Current = (short)(TrameHID[3] + (TrameHID[4] << 8));
                    CurrentHidValue.Axe[2].State_Current = (short)(TrameHID[5] + (TrameHID[6] << 8));
                    break;

                case 2:

                    CurrentHidValue.Axe[3].State_Current = (short)(TrameHID[1] + (TrameHID[2] << 8));
                    CurrentHidValue.Axe[4].State_Current = (short)((TrameHID[3] + (TrameHID[4] << 8)) * -1);
                    CurrentHidValue.Axe[5].State_Current = (short)(TrameHID[5] + (TrameHID[6] << 8));
                    break;

                case 3:
                 
                    for (int BclBtn = 0; BclBtn < CurrentHidValue.NbBtn; BclBtn++)
                    {
                        byte BitMask = (byte) (1 << (BclBtn % 8));
                        CurrentHidValue.Btn[BclBtn].State_Current = (TrameHID[(BclBtn / 8)+1] & BitMask) == BitMask;
                    }
 
                    break;

                case (byte) OutputValue.REPORT_ID_CMD:
                    CurrentHidValue.ProfilNum = (short)(TrameHID[2] + (TrameHID[3] << 8));
                    CurrentHidValue.IsRBC9Present = ((short)(TrameHID[1]) != 0) ? true : false;
                    break;

            }
        }

        #endregion

        #region Overrides

        protected override void HandleDataReceived(InputReport oInRep)
        {
            BuzzInputReport oBuzIn = (BuzzInputReport)oInRep;
            Parse_TrameHID(oBuzIn.TrameHID);
            if (OnButtonChanged != null)
            {
                OnButtonChanged(this, new HIDChangedEventArgs(CurrentHidValue));
            }
        }

        protected override void HandleDeviceRemoved()
        {

            if (OnDeviceRemoved != null)
            {
                OnDeviceRemoved(this, new HIDChangedEventArgs(CurrentHidValue));
            }

        }


        protected override void Dispose(bool bDisposing)
        {
            if (bDisposing)
            {
                // before we go, turn all lights off
                //SetLights(0);
            }
            base.Dispose(bDisposing);
        }
        #endregion
    }

    #region Device reports

    public class BuzzOutputReport : OutputReport
    {
        public BuzzOutputReport(HIDDevice oDev) : base(oDev) { }
       
        public void SetOutput(OutputValue Command, bool bLight)
        {
            byte[] arrBuff = Buffer;

            arrBuff[0] = (byte) OutputValue.REPORT_ID_CMD;
            arrBuff[1] = (byte) Command;
            arrBuff[2] = (byte)(bLight ? 1 : 0);
        }

        public void SetOutput(OutputValue Command)
        {
            byte[] arrBuff = Buffer;

            arrBuff[0] = (byte) OutputValue.REPORT_ID_CMD;
            arrBuff[1] = (byte) Command;
        }

        public void SetOutput(OutputValue Command, short NumProfil)
        {
            byte[] arrBuff = Buffer;

            arrBuff[0] = (byte) OutputValue.REPORT_ID_CMD;
            arrBuff[1] = (byte) Command;
            arrBuff[2] = (byte)(NumProfil & 0x00ff);
            arrBuff[3] = (byte)((NumProfil & 0xff00) >> 8);

        }
    }

    public class BuzzInputReport : InputReport
    {
        private byte[] m_TrameHID;
        public BuzzInputReport(HIDDevice oDev)
            : base(oDev)
        {
            m_TrameHID = new byte[oDev.InputReportLength];
        }

        public override void ProcessData()
        {
            m_TrameHID = Buffer;
        }

        public byte[] TrameHID
        {
            get
            {
                return m_TrameHID;
            }
        }
    }
    #endregion
}
using System;
using System.Text;
using System.Runtime.InteropServices;

namespace USB_HID
{
	/// <summary>
	/// Class that wraps USB API calls and structures
	/// </summary>
    public class Win32Usb
    {
        #region Structures
        /// <summary>
        /// An overlapped structure used for overlapped IO operations. The structure is
        /// only used by the OS to keep state on pending operations. You don't need to fill anything in if you
        /// unless you want a Windows event to fire when the operation is complete.
        /// </summary>
        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        protected struct Overlapped
        {
            public uint Internal;
            public uint InternalHigh;
            public uint Offset;
            public uint OffsetHigh;
            public IntPtr Event;
        }
		
		/// <summary>
		/// Provides the capabilities of a HID device
		/// </summary>
        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        protected struct HidCaps
        {
            public short Usage;
            public short UsagePage;
            public short InputReportByteLength;
            public short OutputReportByteLength;
            public short FeatureReportByteLength;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 17)]
            public short[] Reserved;
            public short NumberLinkCollectionNodes;
            public short NumberInputButtonCaps;
            public short NumberInputValueCaps;
            public short NumberInputDataIndices;
            public short NumberOutputButtonCaps;
            public short NumberOutputValueCaps;
            public short NumberOutputDataIndices;
            public short NumberFeatureButtonCaps;
            public short NumberFeatureValueCaps;
            public short NumberFeatureDataIndices;
        }
		
		/// <summary>
		/// Used when registering a window to receive messages about devices added or removed from the system.
		/// </summary>
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
        public class DeviceBroadcastInterface
        {
            public int Size;
            public int DeviceType;
            public int Reserved;
            public Guid ClassGuid;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
            public string Name;
        }

        [StructLayout(LayoutKind.Sequential)]

        public struct SP_DEVINFO_DATA2
        {

            public int cbSize;

            public Guid ClassGuid;

            public int DevInst;

            public int Reserved;

        }

        [StructLayout(LayoutKind.Sequential)]
        public class SP_DEVINFO_DATA
        {
            public int cbSize = Marshal.SizeOf(typeof(SP_DEVINFO_DATA));
            public Guid classGuid = Guid.Empty; // temp
            public int devInst = 0; // dumy
            public int reserved = 0;
        }

        [StructLayout(LayoutKind.Sequential, Pack = 2)]
        public struct SP_DEVICE_INTERFACE_DETAIL_DATA
        {
            public int cbSize;
            public short devicePath;
        }

        [StructLayout(LayoutKind.Sequential)]
        public class SP_DEVICE_INTERFACE_DATA
        {
            public int cbSize = Marshal.SizeOf(typeof(SP_DEVICE_INTERFACE_DATA));
            public Guid interfaceClassGuid = Guid.Empty; // temp
            public int flags = 0;
            public int reserved = 0;
        }


        [StructLayout(LayoutKind.Sequential)]
        public struct SP_CLASSINSTALL_HEADER
        {
            public int cbSize;
            public int InstallFunction;
        }

        [StructLayout(LayoutKind.Sequential)]

        public struct SP_PROPCHANGE_PARAMS
        {
            public SP_CLASSINSTALL_HEADER ClassInstallHeader;
            public int StateChange;
            public int Scope;
            public int HwProfile;
            public void Init()
            {
                ClassInstallHeader = new SP_CLASSINSTALL_HEADER();
            }
        }



        #endregion

        #region Constants
		/// <summary>Windows message sent when a device is inserted or removed</summary>
		public const int WM_DEVICECHANGE = 0x0219;
		/// <summary>WParam for above : A device was inserted</summary>
		public const int DEVICE_ARRIVAL = 0x8000;
		/// <summary>WParam for above : A device was removed</summary>
		public const int DEVICE_REMOVECOMPLETE = 0x8004;
		/// <summary>Used in SetupDiClassDevs to get devices present in the system</summary>
        protected const int DIGCF_PRESENT = 0x02;
		/// <summary>Used in SetupDiClassDevs to get device interface details</summary>
		protected const int DIGCF_DEVICEINTERFACE = 0x10;
		/// <summary>Used when registering for device insert/remove messages : specifies the type of device</summary>
		protected const int DEVTYP_DEVICEINTERFACE = 0x05;
		/// <summary>Used when registering for device insert/remove messages : we're giving the API call a window handle</summary>
		protected const int DEVICE_NOTIFY_WINDOW_HANDLE = 0;
        /// <summary>Purges Win32 transmit buffer by aborting the current transmission.</summary>
        protected const uint PURGE_TXABORT = 0x01;
        /// <summary>Purges Win32 receive buffer by aborting the current receive.</summary>
        protected const uint PURGE_RXABORT = 0x02;
        /// <summary>Purges Win32 transmit buffer by clearing it.</summary>
        protected const uint PURGE_TXCLEAR = 0x04;
        /// <summary>Purges Win32 receive buffer by clearing it.</summary>
        protected const uint PURGE_RXCLEAR = 0x08;
        /// <summary>CreateFile : Open file for read</summary>
        protected const uint GENERIC_READ = 0x80000000;
        /// <summary>CreateFile : Open file for write</summary>
        protected const uint GENERIC_WRITE = 0x40000000;

        protected const uint FILE_SHARE_READ = 0x01;
        protected const uint FILE_SHARE_WRITE = 0x02;


        /// <summary>CreateFile : Open handle for overlapped operations</summary>
        protected const uint FILE_FLAG_OVERLAPPED = 0x40000000;
        /// <summary>CreateFile : Resource to be "created" must exist</summary>
        protected const uint OPEN_EXISTING = 3;
        /// <summary>ReadFile/WriteFile : Overlapped operation is incomplete.</summary>
        protected const uint ERROR_IO_PENDING = 997;
        /// <summary>Infinite timeout</summary>
        protected const uint INFINITE = 0xFFFFFFFF;
        /// <summary>Simple representation of a null handle : a closed stream will get this handle. Note it is public for comparison by higher level classes.</summary>
        public static IntPtr NullHandle = IntPtr.Zero;
        /// <summary>Simple representation of the handle returned when CreateFile fails.</summary>
        protected static IntPtr InvalidHandleValue = new IntPtr(-1);

        public const int DIF_PROPERTYCHANGE = 0x00000012;

        public const int DICS_ENABLE = 0x00000001;
        public const int DICS_DISABLE = 0x00000002;
        public const int DICS_PROPCHANGE = 0x00000003;
        public const int DICS_START = 0x00000004;
        public const int DICS_STOP = 0x00000005;
        public const int DICS_FLAG_GLOBAL = 0x00000001;


        #endregion

        #region P/Invoke
		/// <summary>
		/// Gets the GUID that Windows uses to represent HID class devices
		/// </summary>
		/// <param name="gHid">An out parameter to take the Guid</param>
        [DllImport("hid.dll",      SetLastError = true)] protected static extern void HidD_GetHidGuid(out Guid gHid);
		/// <summary>
		/// Allocates an InfoSet memory block within Windows that contains details of devices.
		/// </summary>
		/// <param name="gClass">Class guid (e.g. HID guid)</param>
		/// <param name="strEnumerator">Not used</param>
		/// <param name="hParent">Not used</param>
		/// <param name="nFlags">Type of device details required (DIGCF_ constants)</param>
		/// <returns>A reference to the InfoSet</returns>
        [DllImport("setupapi.dll", SetLastError = true)] protected static extern IntPtr SetupDiGetClassDevs(ref Guid gClass, [MarshalAs(UnmanagedType.LPStr)] string strEnumerator, IntPtr hParent, uint nFlags);
		/// <summary>
		/// Frees InfoSet allocated in call to above.
		/// </summary>
		/// <param name="lpInfoSet">Reference to InfoSet</param>
		/// <returns>true if successful</returns>
		[DllImport("setupapi.dll", SetLastError = true)] protected static extern int SetupDiDestroyDeviceInfoList(IntPtr lpInfoSet);
		/// <summary>
		/// Gets the DeviceInterfaceData for a device from an InfoSet.
		/// </summary>
		/// <param name="lpDeviceInfoSet">InfoSet to access</param>
		/// <param name="nDeviceInfoData">Not used</param>
		/// <param name="gClass">Device class guid</param>
		/// <param name="nIndex">Index into InfoSet for device</param>
		/// <param name="oInterfaceData">DeviceInterfaceData to fill with data</param>
		/// <returns>True if successful, false if not (e.g. when index is passed end of InfoSet)</returns>
        [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
        internal static extern bool SetupDiEnumDeviceInterfaces(
            IntPtr deviceInfoSet,
            SP_DEVINFO_DATA deviceInfoData,
            ref Guid interfaceClassGuid,
            int memberIndex,
            SP_DEVICE_INTERFACE_DATA deviceInterfaceData);
        
        /// <summary>
		/// SetupDiGetDeviceInterfaceDetail - two of these, overloaded because they are used together in slightly different
		/// ways and the parameters have different meanings.
		/// Gets the interface detail from a DeviceInterfaceData. This is pretty much the device path.
		/// You call this twice, once to get the size of the struct you need to send (nDeviceInterfaceDetailDataSize=0)
		/// and once again when you've allocated the required space.
		/// </summary>
		/// <param name="lpDeviceInfoSet">InfoSet to access</param>
		/// <param name="oInterfaceData">DeviceInterfaceData to use</param>
		/// <param name="lpDeviceInterfaceDetailData">DeviceInterfaceDetailData to fill with data</param>
		/// <param name="nDeviceInterfaceDetailDataSize">The size of the above</param>
		/// <param name="nRequiredSize">The required size of the above when above is set as zero</param>
		/// <param name="lpDeviceInfoData">Not used</param>
		/// <returns></returns>
        [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
        protected static extern bool SetupDiGetDeviceInterfaceDetail(
            IntPtr deviceInfoSet,
            SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
            IntPtr deviceInterfaceDetailData,
            int deviceInterfaceDetailDataSize,
            ref int requiredSize,
            SP_DEVINFO_DATA deviceInfoData);


        [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
        protected static extern bool SetupDiSetClassInstallParams(
        IntPtr DeviceInfoSet,
        ref SP_DEVINFO_DATA2 DeviceInfoData,
        ref SP_CLASSINSTALL_HEADER ClassInstallParams,
        int ClassInstallParamsSize);

        [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
        protected static extern bool SetupDiCallClassInstaller(
        int InstallFunction,
        IntPtr DeviceInfoSet,
        ref SP_DEVINFO_DATA2 DeviceInfoData);



        [DllImport("setupapi.dll")]

        public static extern bool SetupDiEnumDeviceInfo(
        IntPtr DeviceInfoSet,
        int Supplies,
        ref SP_DEVINFO_DATA2 DeviceInfoData);

      
        /// <summary>
		/// Registers a window for device insert/remove messages
		/// </summary>
		/// <param name="hwnd">Handle to the window that will receive the messages</param>
		/// <param name="lpInterface">DeviceBroadcastInterrface structure</param>
		/// <param name="nFlags">set to DEVICE_NOTIFY_WINDOW_HANDLE</param>
		/// <returns>A handle used when unregistering</returns>
        [DllImport("user32.dll",   SetLastError = true)] protected static extern IntPtr RegisterDeviceNotification(IntPtr hwnd, DeviceBroadcastInterface oInterface, uint nFlags);
		/// <summary>
		/// Unregister from above.
		/// </summary>
		/// <param name="hHandle">Handle returned in call to RegisterDeviceNotification</param>
		/// <returns>True if success</returns>
        [DllImport("user32.dll",   SetLastError = true)] protected static extern bool UnregisterDeviceNotification(IntPtr hHandle);
		/// <summary>
		/// Gets details from an open device. Reserves a block of memory which must be freed.
		/// </summary>
		/// <param name="hFile">Device file handle</param>
		/// <param name="lpData">Reference to the preparsed data block</param>
		/// <returns></returns>
		[DllImport("hid.dll",      SetLastError = true)] protected static extern bool HidD_GetPreparsedData(IntPtr hFile, out IntPtr lpData);

        [DllImport("hid.dll")] 
        static public extern bool HidD_SetOutputReport(IntPtr HidDeviceObject, ref byte lpReportBuffer, int ReportBufferLength);
        
        /// <summary>
		/// Frees the memory block reserved above.
		/// </summary>
		/// <param name="pData">Reference to preparsed data returned in call to GetPreparsedData</param>
		/// <returns></returns>
		[DllImport("hid.dll",      SetLastError = true)] protected static extern bool HidD_FreePreparsedData(ref IntPtr pData);
		/// <summary>
		/// Gets a device's capabilities from the preparsed data.
		/// </summary>
		/// <param name="lpData">Preparsed data reference</param>
		/// <param name="oCaps">HidCaps structure to receive the capabilities</param>
		/// <returns>True if successful</returns>
		[DllImport("hid.dll",      SetLastError = true)] protected static extern int HidP_GetCaps(IntPtr lpData, out HidCaps oCaps);
		/// <summary>
		/// Creates/opens a file, serial port, USB device... etc
		/// </summary>
		/// <param name="strName">Path to object to open</param>
		/// <param name="nAccess">Access mode. e.g. Read, write</param>
		/// <param name="nShareMode">Sharing mode</param>
		/// <param name="lpSecurity">Security details (can be null)</param>
		/// <param name="nCreationFlags">Specifies if the file is created or opened</param>
		/// <param name="nAttributes">Any extra attributes? e.g. open overlapped</param>
		/// <param name="lpTemplate">Not used</param>
		/// <returns></returns>
		[DllImport("kernel32.dll", SetLastError = true)] protected static extern IntPtr CreateFile([MarshalAs(UnmanagedType.LPStr)] string strName, uint nAccess, uint nShareMode, IntPtr lpSecurity, uint nCreationFlags, uint nAttributes, IntPtr lpTemplate);
		/// <summary>
		/// Closes a window handle. File handles, event handles, mutex handles... etc
		/// </summary>
		/// <param name="hFile">Handle to close</param>
		/// <returns>True if successful.</returns>
		[DllImport("kernel32.dll", SetLastError = true)] protected static extern int CloseHandle(IntPtr hFile);
        #endregion

		#region Public methods
		/// <summary>
		/// Registers a window to receive windows messages when a device is inserted/removed. Need to call this
		/// from a form when its handle has been created, not in the form constructor. Use form's OnHandleCreated override.
		/// </summary>
		/// <param name="hWnd">Handle to window that will receive messages</param>
		/// <param name="gClass">Class of devices to get messages for</param>
		/// <returns>A handle used when unregistering</returns>
        public static IntPtr RegisterForUsbEvents(IntPtr hWnd, Guid gClass)
        {
			DeviceBroadcastInterface oInterfaceIn = new DeviceBroadcastInterface();
            oInterfaceIn.Size = Marshal.SizeOf(oInterfaceIn);
			oInterfaceIn.ClassGuid = gClass;
			oInterfaceIn.DeviceType = DEVTYP_DEVICEINTERFACE;
            oInterfaceIn.Reserved = 0;
			return RegisterDeviceNotification(hWnd, oInterfaceIn, DEVICE_NOTIFY_WINDOW_HANDLE);
        }
		/// <summary>
		/// Unregisters notifications. Can be used in form dispose
		/// </summary>
		/// <param name="hHandle">Handle returned from RegisterForUSBEvents</param>
		/// <returns>True if successful</returns>
        public static bool UnregisterForUsbEvents(IntPtr hHandle)
        {
            return UnregisterDeviceNotification(hHandle);
        }
		/// <summary>
		/// Helper to get the HID guid.
		/// </summary>
        public static Guid HIDGuid
        {
            get
            {
                Guid gHid;
                HidD_GetHidGuid(out gHid);
                return gHid;
            }
        }
		#endregion
    }
}
using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Microsoft.Win32;
using Utilitaires;
using System.IO;
using System.Media;
using System.Runtime.InteropServices;

namespace RBC9___HID
{
    class MXApp
    {
        private string _AppName;
        public MXApp(string vAppName)
        {
            this._AppName = vAppName;
        }

        public string AppName
        {
            get { return _AppName; }
            set { _AppName = value; }
        }
    }

    class MXLayout
    {
        private string _LayoutKey;
        private string _LayoutName;
        public byte[] _XMLUser;
        public ArrayList _AppLst = new ArrayList();

        public MXLayout(string vLayoutKey)
        {
            ModifyRegistry myRegistry = new ModifyRegistry();
            myRegistry.BaseRegistryKey = Registry.LocalMachine;

            this._LayoutKey = vLayoutKey;

            myRegistry.SubKey = "Software\\RBC9\\MX1000\\" + _LayoutKey;

            this._LayoutName = myRegistry.ReadString("LayoutName");

            string[] AppLst = (string[])myRegistry.Read("AppLst");
            if (AppLst != null)
            {
                foreach (string AppName in AppLst)
                {
                    _AppLst.Add(new MXApp(AppName));
                }
            }

            _XMLUser = myRegistry.ReadBinary("XMLUser");
        }

        public MXLayout(string vLayoutKey, string vLayoutName)
        {
            this._LayoutKey = vLayoutKey;
            this._LayoutName = vLayoutName;

        }

        public void Save()
        {
            ModifyRegistry myRegistry = new ModifyRegistry();
            myRegistry.BaseRegistryKey = Registry.LocalMachine;
            myRegistry.SubKey = "Software\\RBC9\\MX1000\\" + _LayoutKey;

            myRegistry.Write("LayoutName", _LayoutName);

            if (_AppLst.Count > 0)
            {
                string[] AppLst = new string[_AppLst.Count];
                int bclapp = 0;
                foreach (MXApp AppName in _AppLst)
                {
                    AppLst[bclapp++] = AppName.AppName;
                }
                myRegistry.Write("AppLst", AppLst);
            }
            else
            {
                myRegistry.DeleteKey("AppLst");
            }

            myRegistry.Write("XMLUser", _XMLUser);
        }

        public void ReadUserXml()
        {
            ModifyRegistry myRegistry = new ModifyRegistry();

            myRegistry.BaseRegistryKey = Registry.CurrentUser;
            myRegistry.SubKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders";
            string MX_UserXml = myRegistry.Read("AppData") + "\\Logitech\\SetPoint\\user.xml";

            if (File.Exists(MX_UserXml))
            {
                _XMLUser = File.ReadAllBytes(MX_UserXml);
            }

        }

        public void WriteUserXml()
        {
            ModifyRegistry myRegistry = new ModifyRegistry();

            myRegistry.BaseRegistryKey = Registry.CurrentUser;
            myRegistry.SubKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders";
            string MX_UserXml = myRegistry.Read("AppData") + "\\Logitech\\SetPoint\\user.xml";


            if (_XMLUser != null)
            {
                if (_XMLUser.Length > 0)
                {
                    File.WriteAllBytes(MX_UserXml, _XMLUser);
                    
                    // File.WriteAllBytes("c:\\toto.txt", _XMLUser);
                }
            }

        }

        public string LayoutName
        {
            get { return _LayoutName; }
            set { _LayoutName = value; }
        }

        public string LayoutKey
        {
            get { return _LayoutKey; }
            set { _LayoutKey = value; }
        }
    }

    public class MX1000
    {

        private ModifyRegistry myRegistry;
        private string SetPointExe;
        private string MX_UserXml;
        private string RegKey = "Software\\RBC9\\MX1000";

        private Thread Thread_AutoSwitch;
        private bool Thread_AutoSwitch_Running;

        public bool SetPointOk;
        public string DefaultLayout;
        public bool   AutoSwitch;
        private bool _CurrentAuto;


        public ArrayList _Layout = new ArrayList();

        public MX1000()
        {
            InitPath();
            Load();
   

        }

        public void Dispose()
        {
            AutoSwitch_Stop();
            GC.SuppressFinalize(this);
        }

        ~MX1000()
        {
            Dispose();
        }

        public bool CurrentAuto
        {
            get
            {
                return _CurrentAuto;

            }
            set {

                _CurrentAuto = value;

                if (_CurrentAuto)
                {
                    AutoSwitch_Start();
                }
                else
                {
                    AutoSwitch_Stop();
                }
       
            }
        }


        private void InitPath()
        {

            myRegistry = new ModifyRegistry();

            myRegistry.BaseRegistryKey = Registry.LocalMachine;
            myRegistry.SubKey = "Software\\Logitech\\SetPoint\\CurrentVersion\\Setup";
            SetPointExe = myRegistry.Read("SetPoint Directory") + "\\SetPoint.exe";

            SetPointOk = File.Exists(SetPointExe);

            myRegistry.BaseRegistryKey = Registry.CurrentUser;
            myRegistry.SubKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders";
            MX_UserXml = myRegistry.Read("AppData") + "\\Logitech\\SetPoint\\user.xml";

            myRegistry.BaseRegistryKey = Registry.LocalMachine;
            myRegistry.SubKey = "Software\\RBC9\\MX1000";
        }

        public void Load()
        {

            DefaultLayout = myRegistry.ReadString("DefaultLayout");
            AutoSwitch = (myRegistry.ReadInt32("AutoSwitch") != 0) ? true : false;

            

            string[] LayoutLst = myRegistry.SubKeyNames();

            _Layout.Clear();

            if (LayoutLst != null)
            {
                foreach (string LayoutKey in LayoutLst)
                {
                    if (LayoutKey.IndexOf("Layout - ") == 0)
                    {
                        _Layout.Add(new MXLayout(LayoutKey));
                    }
                }
            }

            CurrentAuto = AutoSwitch;

        }

        public string NextKey()
        {
            int MaxNum = 0;
            int NumLayout;

            string[] LayoutLst = myRegistry.SubKeyNames();

            if (LayoutLst != null)
            {
                foreach (string LayoutKey in LayoutLst)
                {
                    if (LayoutKey.IndexOf("Layout - ") == 0)
                    {

                        NumLayout = int.Parse(LayoutKey.Substring(10, 4));
                        if (NumLayout > MaxNum)
                        {
                            MaxNum = NumLayout;
                        }


                    }
                }
            }
            MaxNum++;
            return "Layout - " + MaxNum.ToString("[0000]");
        }

        public int AddNew()
        {
            return _Layout.Add(new MXLayout(NextKey(), "- New Layout -"));
        }

        public void Save()
        {
            myRegistry.SubKey = RegKey;
            myRegistry.DeleteSubKeyTree();

            myRegistry.Write("DefaultLayout", DefaultLayout);
            myRegistry.Write("AutoSwitch", AutoSwitch ? 1 : 0);

            foreach (MXLayout Layout in _Layout)
            {
                Layout.Save();
            }
        }

        private void AutoSwitch_Start()
        {
            if (SetPointOk)
            {
                AutoSwitch_Stop();
                Thread_AutoSwitch_Running = true;
                Thread_AutoSwitch = new Thread(new ThreadStart(AutoSwitch_CheckAppli));
                Thread_AutoSwitch.Start();
            }
        }


        public void AutoSwitch_Stop()
        {
            if (SetPointOk)
            {
                Thread_AutoSwitch_Running = false;
                if (Thread_AutoSwitch != null)
                {
                    Thread_AutoSwitch.Abort();
                    while (Thread_AutoSwitch.IsAlive)
                    {
                        Thread.Sleep(500);
                    }
                }
            }
            Thread_AutoSwitch = null;
        }


        private void AutoSwitch_CheckAppli()
        {
            
            string[] LstProcExecpt = { "SYSTEM", "IDLE", "audiodg" };
 
            System.Diagnostics.Process[] LstProcess;

            string NewProfil = "";
            string LastSwitch = "???";
 

            while (Thread_AutoSwitch_Running)
            {
               // Debug.WriteLine("----- MX Auto");
                NewProfil = DefaultLayout;

                foreach (MXLayout MyMxLayout in _Layout)
                {
                    foreach (MXApp MyMxApp in MyMxLayout._AppLst)
                    {

                        LstProcess = Process.GetProcessesByName(MyMxApp.AppName.ToUpper());
                        if (LstProcess != null)
                        {
                            if (LstProcess.Length > 0)
                            {
                                //Debug.WriteLine("Found " + MyMxApp.AppName.ToUpper());
                                NewProfil = MyMxLayout.LayoutKey;
                            }
                        }
                    }
                }

                if (NewProfil != LastSwitch)
                {

                    Debug.WriteLine("Switch to " + NewProfil);
                    Switch(NewProfil);
                }

                LastSwitch = NewProfil;

                Thread.Sleep(2000);
            }
        }

        public void Switch(string LayoutKey)
        {
            if (SetPointOk)
            {
                SetPoint_Stop();

                foreach (MXLayout MyMxLayout in _Layout)
                {
                    if (MyMxLayout.LayoutKey == LayoutKey)
                    {
                        MyMxLayout.WriteUserXml();
                        break;
                    }
                }

                SetPoint_Start();
            }
        }

 

        private void SetPoint_Stop()
        {


            System.Diagnostics.Process[] prc = Process.GetProcessesByName("SETPOINT");

            for (int i = 0; i < prc.Length; i++)
            {

                    prc[i].CloseMainWindow();
                    prc[i].Kill();
                    prc[i].Dispose();
                    prc[i].Close();
                
            }
        }

        private void SetPoint_Start()
        {
            Process proc = new Process();
            proc.StartInfo.FileName = SetPointExe;
            proc.Start();
            proc.CloseMainWindow();
            proc.Close();
        }

    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Utilitaires;

namespace RBC9___HID
{
    public partial class ParamMX1000 : Form
    {

        MX1000 MyMx;

        public ParamMX1000(MX1000 MyMx1000)
        {
            InitializeComponent();
            MyMx = MyMx1000;
        }

        private void ParamMX1000_Load(object sender, EventArgs e)
        {

            layoutBindingSource.DataSource = MyMx._Layout;
            DefaultbindingSource.DataSource = MyMx._Layout;
            Synchro_AppLst();
            if (MyMx.DefaultLayout!= null)
                cboDefault.SelectedValue = MyMx.DefaultLayout;

            chkAuto.Checked = MyMx.AutoSwitch;

        }

        void Synchro_AppLst()
        {

            if (layoutBindingSource.Current != null)
            {

                layoutAppAutoBindingSource.DataSource = ((MXLayout)layoutBindingSource.Current)._AppLst;
            }
            else
            {
                layoutAppAutoBindingSource.DataSource = null;
            }

            layoutAppAutoBindingSource.ResetBindings(false);

            DefaultbindingSource.ResetBindings(false);
        }
     
        private void btnQuit_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(
                "Quit without Save ?",
                "RBC9 - MX1000",
                MessageBoxButtons.YesNo)
                == DialogResult.Yes)
            {
                this.Close();
            }
        }

      
        private void btnLayoutAdd_Click(object sender, EventArgs e)
        {
            int NewPos = MyMx.AddNew();
            layoutBindingSource.ResetBindings(false);
            layoutBindingSource.Position = NewPos;
            Synchro_AppLst();
        }

        private void btnLayoutDel_Click(object sender, EventArgs e)
        {
            if (layoutBindingSource.Current != null)
            {
                if (MessageBox.Show(
                "<" + ((MXLayout)layoutBindingSource.Current).LayoutName + "> ?",
                "Delete Layout",
                MessageBoxButtons.YesNo)
                == DialogResult.Yes)
                {
                    layoutBindingSource.RemoveCurrent();
                    Synchro_AppLst();
                }
            }
        }

        private void gridLayout_SelectionChanged(object sender, EventArgs e)
        {
            Synchro_AppLst();
        }

        private void btnDelAppAuto_Click(object sender, EventArgs e)
        {

            if (layoutAppAutoBindingSource.Current != null)
            {
                if (MessageBox.Show(
                "<" + ((MXApp)layoutAppAutoBindingSource.Current).AppName + "> ?",
                "Delete App",
                MessageBoxButtons.YesNo)
                == DialogResult.Yes)
                {
                    layoutAppAutoBindingSource.RemoveCurrent();

                }
            }
        }

        private void btnAddAppAuto_Click(object sender, EventArgs e)
        {

            if (layoutBindingSource.Current == null) return;


            MXApp NewApp = new MXApp("< New App >");

            ((MXLayout)layoutBindingSource.Current)._AppLst.Add(NewApp);


            layoutAppAutoBindingSource.ResetBindings(true);
            layoutAppAutoBindingSource.Position = layoutAppAutoBindingSource.IndexOf(NewApp);

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (layoutBindingSource.Current == null) return;

            if (MessageBox.Show(
                "Update this Layout from Current SetPoint File ?",
                "Update",
                MessageBoxButtons.YesNo)
                == DialogResult.Yes)
            {
                ((MXLayout)layoutBindingSource.Current).ReadUserXml();

            }
           

        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(
              "Apply New Layout ?",
              "RBC9 - MX1000",
              MessageBoxButtons.YesNo)
              == DialogResult.Yes)
            {
                MyMx.Save();
                this.Close();

            }
        }

        private void cboDefault_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox MyDefault = (ComboBox)sender;

            if (MyDefault.SelectedItem == null) return;

            MyMx.DefaultLayout = (string)MyDefault.SelectedValue;
        }

        private void chkAuto_CheckedChanged(object sender, EventArgs e)
        {

            CheckBox MyAuto = (CheckBox)sender;

            if (MyAuto == null) return;
            
           MyMx.AutoSwitch = MyAuto.Checked;
        }

       
       
    }
}﻿namespace RBC9___HID
{
    partial class ParamMX1000
    {
        /// <summary>
        /// Variable nécessaire au concepteur.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Nettoyage des ressources utilisées.
        /// </summary>
        /// <param name="disposing">true si les ressources managées doivent être supprimées ; sinon, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Code généré par le Concepteur Windows Form

        /// <summary>
        /// Méthode requise pour la prise en charge du concepteur - ne modifiez pas
        /// le contenu de cette méthode avec l'éditeur de code.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle4 = new System.Windows.Forms.DataGridViewCellStyle();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ParamMX1000));
            this.btnQuit = new System.Windows.Forms.Button();
            this.gridLayout = new System.Windows.Forms.DataGridView();
            this.layoutNameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.layoutBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.btnLayoutDel = new System.Windows.Forms.Button();
            this.btnLayoutAdd = new System.Windows.Forms.Button();
            this.gridApp = new System.Windows.Forms.DataGridView();
            this.appNameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.layoutAppAutoBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.btnDelAppAuto = new System.Windows.Forms.Button();
            this.btnAddAppAuto = new System.Windows.Forms.Button();
            this.button1 = new System.Windows.Forms.Button();
            this.btnApply = new System.Windows.Forms.Button();
            this.cboDefault = new System.Windows.Forms.ComboBox();
            this.DefaultbindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.grpDefault = new System.Windows.Forms.GroupBox();
            this.chkAuto = new System.Windows.Forms.CheckBox();
            ((System.ComponentModel.ISupportInitialize)(this.gridLayout)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.layoutBindingSource)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.gridApp)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.layoutAppAutoBindingSource)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.DefaultbindingSource)).BeginInit();
            this.grpDefault.SuspendLayout();
            this.SuspendLayout();
            // 
            // btnQuit
            // 
            this.btnQuit.Font = new System.Drawing.Font("Comic Sans MS", 12F, System.Drawing.FontStyle.Italic);
            this.btnQuit.Location = new System.Drawing.Point(495, 299);
            this.btnQuit.Name = "btnQuit";
            this.btnQuit.Size = new System.Drawing.Size(80, 32);
            this.btnQuit.TabIndex = 12;
            this.btnQuit.Text = "Cancel";
            this.btnQuit.Click += new System.EventHandler(this.btnQuit_Click);
            // 
            // gridLayout
            // 
            this.gridLayout.AllowUserToAddRows = false;
            this.gridLayout.AllowUserToDeleteRows = false;
            this.gridLayout.AllowUserToResizeColumns = false;
            this.gridLayout.AllowUserToResizeRows = false;
            this.gridLayout.AutoGenerateColumns = false;
            this.gridLayout.BackgroundColor = System.Drawing.Color.WhiteSmoke;
            dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
            dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control;
            dataGridViewCellStyle1.Font = new System.Drawing.Font("Comic Sans MS", 9.75F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
            dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
            dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
            dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
            this.gridLayout.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
            this.gridLayout.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.gridLayout.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.layoutNameDataGridViewTextBoxColumn});
            this.gridLayout.DataSource = this.layoutBindingSource;
            this.gridLayout.Location = new System.Drawing.Point(24, 87);
            this.gridLayout.Name = "gridLayout";
            this.gridLayout.RowHeadersVisible = false;
            this.gridLayout.Size = new System.Drawing.Size(225, 147);
            this.gridLayout.TabIndex = 13;
            this.gridLayout.SelectionChanged += new System.EventHandler(this.gridLayout_SelectionChanged);
            // 
            // layoutNameDataGridViewTextBoxColumn
            // 
            this.layoutNameDataGridViewTextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            this.layoutNameDataGridViewTextBoxColumn.DataPropertyName = "LayoutName";
            dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
            dataGridViewCellStyle2.BackColor = System.Drawing.Color.White;
            this.layoutNameDataGridViewTextBoxColumn.DefaultCellStyle = dataGridViewCellStyle2;
            this.layoutNameDataGridViewTextBoxColumn.HeaderText = "Layout";
            this.layoutNameDataGridViewTextBoxColumn.Name = "layoutNameDataGridViewTextBoxColumn";
            // 
            // layoutBindingSource
            // 
            this.layoutBindingSource.DataSource = typeof(RBC9___HID.MXLayout);
            // 
            // btnLayoutDel
            // 
            this.btnLayoutDel.Font = new System.Drawing.Font("Comic Sans MS", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnLayoutDel.Location = new System.Drawing.Point(154, 249);
            this.btnLayoutDel.Name = "btnLayoutDel";
            this.btnLayoutDel.Size = new System.Drawing.Size(55, 27);
            this.btnLayoutDel.TabIndex = 95;
            this.btnLayoutDel.Text = "Del";
            this.btnLayoutDel.UseVisualStyleBackColor = true;
            this.btnLayoutDel.Click += new System.EventHandler(this.btnLayoutDel_Click);
            // 
            // btnLayoutAdd
            // 
            this.btnLayoutAdd.Font = new System.Drawing.Font("Comic Sans MS", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnLayoutAdd.Location = new System.Drawing.Point(28, 249);
            this.btnLayoutAdd.Name = "btnLayoutAdd";
            this.btnLayoutAdd.Size = new System.Drawing.Size(55, 27);
            this.btnLayoutAdd.TabIndex = 96;
            this.btnLayoutAdd.Text = "Add";
            this.btnLayoutAdd.UseVisualStyleBackColor = true;
            this.btnLayoutAdd.Click += new System.EventHandler(this.btnLayoutAdd_Click);
            // 
            // gridApp
            // 
            this.gridApp.AllowUserToAddRows = false;
            this.gridApp.AllowUserToDeleteRows = false;
            this.gridApp.AllowUserToResizeColumns = false;
            this.gridApp.AllowUserToResizeRows = false;
            this.gridApp.AutoGenerateColumns = false;
            this.gridApp.BackgroundColor = System.Drawing.Color.WhiteSmoke;
            dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
            dataGridViewCellStyle3.BackColor = System.Drawing.SystemColors.Control;
            dataGridViewCellStyle3.Font = new System.Drawing.Font("Comic Sans MS", 9.75F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            dataGridViewCellStyle3.ForeColor = System.Drawing.SystemColors.WindowText;
            dataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight;
            dataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
            dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
            this.gridApp.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle3;
            this.gridApp.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.gridApp.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.appNameDataGridViewTextBoxColumn});
            this.gridApp.DataSource = this.layoutAppAutoBindingSource;
            this.gridApp.Location = new System.Drawing.Point(332, 87);
            this.gridApp.Name = "gridApp";
            this.gridApp.RowHeadersVisible = false;
            this.gridApp.Size = new System.Drawing.Size(242, 147);
            this.gridApp.TabIndex = 97;
            // 
            // appNameDataGridViewTextBoxColumn
            // 
            this.appNameDataGridViewTextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            this.appNameDataGridViewTextBoxColumn.DataPropertyName = "AppName";
            dataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
            this.appNameDataGridViewTextBoxColumn.DefaultCellStyle = dataGridViewCellStyle4;
            this.appNameDataGridViewTextBoxColumn.HeaderText = "Application";
            this.appNameDataGridViewTextBoxColumn.Name = "appNameDataGridViewTextBoxColumn";
            // 
            // layoutAppAutoBindingSource
            // 
            this.layoutAppAutoBindingSource.DataSource = typeof(RBC9___HID.MXApp);
            // 
            // btnDelAppAuto
            // 
            this.btnDelAppAuto.Font = new System.Drawing.Font("Comic Sans MS", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnDelAppAuto.Location = new System.Drawing.Point(495, 249);
            this.btnDelAppAuto.Name = "btnDelAppAuto";
            this.btnDelAppAuto.Size = new System.Drawing.Size(55, 27);
            this.btnDelAppAuto.TabIndex = 98;
            this.btnDelAppAuto.Text = "Del";
            this.btnDelAppAuto.UseVisualStyleBackColor = true;
            this.btnDelAppAuto.Click += new System.EventHandler(this.btnDelAppAuto_Click);
            // 
            // btnAddAppAuto
            // 
            this.btnAddAppAuto.Font = new System.Drawing.Font("Comic Sans MS", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnAddAppAuto.Location = new System.Drawing.Point(361, 249);
            this.btnAddAppAuto.Name = "btnAddAppAuto";
            this.btnAddAppAuto.Size = new System.Drawing.Size(55, 27);
            this.btnAddAppAuto.TabIndex = 99;
            this.btnAddAppAuto.Text = "Add";
            this.btnAddAppAuto.UseVisualStyleBackColor = true;
            this.btnAddAppAuto.Click += new System.EventHandler(this.btnAddAppAuto_Click);
            // 
            // button1
            // 
            this.button1.Font = new System.Drawing.Font("Comic Sans MS", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button1.Location = new System.Drawing.Point(12, 299);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(225, 27);
            this.button1.TabIndex = 100;
            this.button1.Text = "Update from Current SetPoint";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // btnApply
            // 
            this.btnApply.Font = new System.Drawing.Font("Comic Sans MS", 12F, System.Drawing.FontStyle.Italic);
            this.btnApply.Location = new System.Drawing.Point(336, 299);
            this.btnApply.Name = "btnApply";
            this.btnApply.Size = new System.Drawing.Size(80, 32);
            this.btnApply.TabIndex = 101;
            this.btnApply.Text = "Apply";
            this.btnApply.Click += new System.EventHandler(this.btnApply_Click);
            // 
            // cboDefault
            // 
            this.cboDefault.BackColor = System.Drawing.SystemColors.Info;
            this.cboDefault.DataSource = this.DefaultbindingSource;
            this.cboDefault.DisplayMember = "LayoutName";
            this.cboDefault.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboDefault.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.cboDefault.FormattingEnabled = true;
            this.cboDefault.Location = new System.Drawing.Point(12, 20);
            this.cboDefault.Name = "cboDefault";
            this.cboDefault.Size = new System.Drawing.Size(225, 23);
            this.cboDefault.TabIndex = 142;
            this.cboDefault.ValueMember = "LayoutKey";
            this.cboDefault.SelectedIndexChanged += new System.EventHandler(this.cboDefault_SelectedIndexChanged);
            // 
            // DefaultbindingSource
            // 
            this.DefaultbindingSource.DataSource = typeof(RBC9___HID.MXLayout);
            // 
            // grpDefault
            // 
            this.grpDefault.Controls.Add(this.cboDefault);
            this.grpDefault.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.grpDefault.Location = new System.Drawing.Point(12, 12);
            this.grpDefault.Name = "grpDefault";
            this.grpDefault.Size = new System.Drawing.Size(244, 49);
            this.grpDefault.TabIndex = 144;
            this.grpDefault.TabStop = false;
            this.grpDefault.Text = "Default Layout";
            // 
            // chkAuto
            // 
            this.chkAuto.AutoSize = true;
            this.chkAuto.Font = new System.Drawing.Font("Comic Sans MS", 8.25F);
            this.chkAuto.Location = new System.Drawing.Point(333, 32);
            this.chkAuto.Name = "chkAuto";
            this.chkAuto.Size = new System.Drawing.Size(86, 19);
            this.chkAuto.TabIndex = 145;
            this.chkAuto.Text = "AutoSwitch";
            this.chkAuto.UseVisualStyleBackColor = true;
            this.chkAuto.CheckedChanged += new System.EventHandler(this.chkAuto_CheckedChanged);
            // 
            // ParamMX1000
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(594, 348);
            this.ControlBox = false;
            this.Controls.Add(this.chkAuto);
            this.Controls.Add(this.grpDefault);
            this.Controls.Add(this.btnApply);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.btnDelAppAuto);
            this.Controls.Add(this.btnAddAppAuto);
            this.Controls.Add(this.gridApp);
            this.Controls.Add(this.btnLayoutDel);
            this.Controls.Add(this.btnLayoutAdd);
            this.Controls.Add(this.gridLayout);
            this.Controls.Add(this.btnQuit);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "ParamMX1000";
            this.Text = "Param MX1000";
            this.Load += new System.EventHandler(this.ParamMX1000_Load);
            ((System.ComponentModel.ISupportInitialize)(this.gridLayout)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.layoutBindingSource)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.gridApp)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.layoutAppAutoBindingSource)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.DefaultbindingSource)).EndInit();
            this.grpDefault.ResumeLayout(false);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button btnQuit;
        private System.Windows.Forms.DataGridView gridLayout;
        private System.Windows.Forms.BindingSource layoutBindingSource;
        private System.Windows.Forms.DataGridViewTextBoxColumn layoutNameDataGridViewTextBoxColumn;
        private System.Windows.Forms.Button btnLayoutDel;
        private System.Windows.Forms.Button btnLayoutAdd;
        private System.Windows.Forms.BindingSource layoutAppAutoBindingSource;
        private System.Windows.Forms.DataGridView gridApp;
     
        private System.Windows.Forms.DataGridViewTextBoxColumn appNameDataGridViewTextBoxColumn;
        private System.Windows.Forms.Button btnDelAppAuto;
        private System.Windows.Forms.Button btnAddAppAuto;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button btnApply;
        private System.Windows.Forms.ComboBox cboDefault;
        private System.Windows.Forms.GroupBox grpDefault;
        private System.Windows.Forms.BindingSource DefaultbindingSource;
        private System.Windows.Forms.CheckBox chkAuto;

    }
}
using System.IO;
using System.Xml;
using System;

namespace Utilitaires
{
	public sealed class ConfigFile
	{
		#region Variables / Structures / Enums
		private XmlDocument cXmlDocument;
		private bool FileOpened;
		private string FileName;
		
		/// <summary>Parametre enregistré.</summary>
		/// <author>Villard Gregory</author>
		/// <history>
		/// <change date="20/10/2005" author="Villard Gregory">Création.</change>
		/// </history>
		public struct Parametre {
			/// <summary>Nom du parametre.</summary>
			public string Key;
			/// <summary>Valeur du parametre.</summary>
			public string Value;
		}
		#endregion
		
		#region "Constructeur"
		/// <summary>Constructeur de la classe</summary>
		/// <param name="Fichier">Chemine complet du fichier de configuration</param>
		/// <author>Villard Gregory</author>
		/// <history>
		/// <change date="02/08/2005" author="Villard Gregory">Création de la méthode.</change>
		/// <change date="19/09/2005" author="Villard Gregory">Modification pour créer le fichier s'il n'existe pas.</change>
		/// </history>
        /// 
        public ConfigFile(string Fichier)
        {

            if (!this.Open(Fichier))
            {
                this.Fin();
                return;
            }
        }

        public ConfigFile(string Fichier,string Directory)
		{
            if (!this.Open(Fichier,Directory))
            {
                this.Fin();
                return;
            }
         	
		}
		#endregion
		
		#region "Destructeur"
		/// <summary>Destructeur de la classe</summary>
		/// <author>Villard Gregory</author>
		/// <history>
		/// <change date="02/08/2005" author="Villard Gregory">Création de la méthode.</change>
		/// </history>
		private void Fin()
		{
			cXmlDocument = null;
		}
		#endregion
		
		#region "Procédure de fermeture du fichier de config"
		/// <summary>Cette fonction permet de fermer un fichier de configuration ouvert</summary>
		/// <author>Villard Gregory</author>
		/// <history>
		/// <change date="02/08/2005" author="Villard Gregory">Création de la méthode.</change>
		/// </history>
		public void Close()
		{
			FileOpened = false;
			cXmlDocument = null;
			FileName = "";
		}
		#endregion
		
		#region "Procédure d'ouverture du fichier de config"
		/// <summary>Cette fonction permet d'ouvrir un fichier de configuration</summary>
		/// <param name="Fichier">Fichier à ouvrir</param>
		/// <returns>Un Boolean comme réussite de l'ouverture</returns>
		/// <author>Villard Gregory</author>
		/// <history>
		/// <change date="02/08/2005" author="Villard Gregory">Création de la méthode.</change>
		/// <change date="19/09/2005" author="Villard Gregory">Modification pour créer le fichier s'il n'existe pas.</change>
		/// </history>
        /// 
        public bool Open(string Fichier)
        {
            string exepath = Environment.GetCommandLineArgs()[0];
            string exedir = exepath.Substring(0, exepath.LastIndexOf('\\'));
            return Open(Fichier, exedir);

        }


        public bool Open(string Fichier, string Directory)
		{
			FileStream FS;
			StreamWriter SW;
            if (!(File.Exists(Directory+"\\"+Fichier)))
            {
				
				try {
                    FS = new FileStream(Directory + "\\" + Fichier, FileMode.OpenOrCreate);
					SW = new StreamWriter(FS);
                    
					SW.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
					SW.WriteLine("<configuration>");
					SW.WriteLine("  <appSettings>");
					SW.WriteLine("  </appSettings>");
					SW.WriteLine("</configuration>");
					SW.Close();
					SW = null;
					FS.Close();
					FS = null;
				} catch {
                    Console.WriteLine("Erreur 6");
					return false;
				}
				
			}
			
			if (FileOpened) {
				return false;
			} else {
				try {
					cXmlDocument = new XmlDocument();
                    cXmlDocument.Load(Directory + "\\" + Fichier);
					FileName = Fichier;
				} catch {
                    Console.WriteLine("Erreur 7");
					return false;
				}
				FileOpened = true;
				return true;
			}
		}
		#endregion
		
		#region "Procédure de création d'une nouvelle rubrique"
		/// <summary>Cette fonction permet de créer une rubrique</summary>
		/// <param name="Rubrique">Rubrique à créer</param>
		/// <returns>Un Boolean comme réussite de la création</returns>
		/// <author>Villard Gregory</author>
		/// <history>
		/// <change date="20/09/2005" author="Villard Gregory">Création de la méthode.</change>
		/// </history>
		private bool CreateNode(string Rubrique)
		{
			XmlNode cXmlNode;
			XmlNode cXmlRoot;
			try {
				cXmlNode = cXmlDocument.DocumentElement.SelectSingleNode("/configuration/" + Rubrique);
				if (cXmlNode == null) {
					cXmlRoot = cXmlDocument.DocumentElement.SelectSingleNode("/configuration");
					cXmlNode = cXmlDocument.CreateNode(XmlNodeType.Element, Rubrique, "");
					cXmlRoot.AppendChild(cXmlNode);
				}
				cXmlDocument.Save(FileName);
				return true;
			} catch {

				return false;
			}
		}
		#endregion
		
		#region "Procédure d'ecriture de parametres"
		/// <summary>Cette fonction permet d'ecrire une valeur dans une clé</summary>
		/// <param name="Valeur">Valeur à ecrire</param>
		/// <param name="Key">Clé à modifier</param>
		/// <param name="Rubrique">Rubrique du fichier de config (par défaut : appSettings)</param>
		/// <returns>Un Boolean comme réussite de l'ecriture</returns>
		/// <author>Villard Gregory</author>
		/// <history>
		/// <change date="02/08/2005" author="Villard Gregory">Création de la méthode.</change>
		/// <change date="20/09/2005" author="Villard Gregory">Ajout de la création de rubrique.</change>
		/// </history>
		public bool SaveParam(string Valeur, string Key)
		{
			return SaveParam(Valeur, Key, "appSettings");
		}
		
		public bool SaveParam(string Valeur, string Key, string Rubrique)
		{
			XmlNode cXmlNode;
			XmlNode cXmlRoot;
			XmlNode cXmlKey;
			XmlNode cXmlValue;
			if (!(FileOpened)) {
				return false;
			}
			cXmlNode = cXmlDocument.DocumentElement.SelectSingleNode("/configuration/" + Rubrique);
			if (cXmlNode == null) {
				if (!(this.CreateNode(Rubrique))) {
					return false;
				}
			}
			cXmlNode = cXmlDocument.DocumentElement.SelectSingleNode("/configuration/" + Rubrique + "/add[@key=\"" + Key + "\"]");
			if (cXmlNode == null) {
				cXmlNode = cXmlDocument.CreateNode(XmlNodeType.Element, "add", "");
				cXmlKey = cXmlDocument.CreateNode(XmlNodeType.Attribute, "key", "");
				cXmlKey.Value = Key;
				cXmlNode.Attributes.SetNamedItem(cXmlKey);
				cXmlValue = cXmlDocument.CreateNode(XmlNodeType.Attribute, "value", "");
				cXmlValue.Value = Valeur;
				cXmlNode.Attributes.SetNamedItem(cXmlValue);
				cXmlRoot = cXmlDocument.DocumentElement.SelectSingleNode("/configuration/" + Rubrique);
				if (!(cXmlRoot == null)) {
					cXmlRoot.AppendChild(cXmlNode);
				} else {
					return false;
				}
			} else {
				cXmlNode.Attributes.GetNamedItem("value").Value = Valeur;
              }
			try {
				cXmlDocument.Save(FileName);
			} catch {
				return false;
			}
			return true;
		}

        public bool DeleteParam( string Key)
        {
            return SaveParam( Key, "appSettings");
        }
        public bool DeleteParam(string Key, string Rubrique)
        {
            XmlNode cXmlNode;

            if (!(FileOpened))
            {
                return false;
            }
            cXmlNode = cXmlDocument.DocumentElement.SelectSingleNode("/configuration/" + Rubrique);
            if (cXmlNode == null)
            {
                if (!(this.CreateNode(Rubrique)))
                {
                    return false;
                }
            }
            cXmlNode = cXmlDocument.DocumentElement.SelectSingleNode("/configuration/" + Rubrique + "/add[@key=\"" + Key + "\"]");
            if (cXmlNode != null)
            {
                cXmlNode.ParentNode.RemoveChild(cXmlNode);
            }
            try
            {
                cXmlDocument.Save(FileName);
            }
            catch
            {
                return false;
            }
            return true;
        }

		#endregion
		
		#region "Procédure de lecture de parametres"
		/// <summary>Cette fonction permet de lire la valeur d'une clé</summary>
		/// <param name="Key">Clé à lire</param>
		/// <param name="Rubrique">Rubrique du fichier de config (par défaut : appSettings)</param>
		/// <returns>Une String comme valeur lue dans la clé</returns>
		/// <author>Villard Gregory</author>
		/// <history>
		/// <change date="02/08/2005" author="Villard Gregory">Création de la méthode.</change>
		/// </history>
		public string ReadParam(string Key)
		{
			return ReadParam(Key, "appSettings");
		}
		public string ReadParam(string Key, string Rubrique)
		{
			XmlNode cXmlNode;
			if (!(FileOpened)) {
				return "ERROR";
			}
			
			cXmlNode = cXmlDocument.DocumentElement.SelectSingleNode("/configuration/" + Rubrique + "/add[@key=\"" + Key + "\"]");
			if (cXmlNode == null) {
				//return "ERROR";
				return "";
			} else {
				return cXmlNode.Attributes.GetNamedItem("value").Value;
			}
		}
		#endregion
		
		#region "Liste des Parametres"
		/// <summary>Cette fonction permet de recupérer les nodes d'une rubrique donnée</summary>
		/// <param name="Rubrique">Rubrique du fichier de config (par défaut : appSettings)</param>
		/// <returns>Un array de Parametre</returns>
		/// <author>Villard Gregory</author>
		/// <history>
		/// <change date="20/10/2005" author="Villard Gregory">Création de la méthode.</change>
		/// </history>
		public Parametre[] Parametres() {
			return Parametres("appSettings");
		}
		public Parametre[] Parametres(string Rubrique) {
			XmlNode cXmlNode;
			XmlNodeList cXmlNodeLst;
			Parametre par;
			int i;
			
			par.Key = "";
			par.Value = "";
			
			if (!FileOpened) {
				// Levée d'une erreur
				return null;
			}
			
			cXmlNode = cXmlDocument.DocumentElement.SelectSingleNode("/configuration/" + Rubrique);
			
			if (cXmlNode == null) {
				// Erreur si node inexistant
				return null;
			}else{
				// Lecture de la valeur
				cXmlNodeLst = cXmlDocument.SelectNodes("/configuration/" + Rubrique + "/descendant::add");
				i = cXmlNodeLst.Count;
				Parametre[] lst = new Parametre[i];
				i = lst.GetLowerBound(0);
				foreach (XmlNode cN in cXmlNodeLst) {
					par.Key = cN.Attributes.GetNamedItem("key").Value;
					par.Value = cN.Attributes.GetNamedItem("value").Value;
					if ((par.Key == "") && (par.Value == "")) break;
					lst.SetValue(par, i);
					i = i + 1;
				}
				return lst;
			}			
		}
		#endregion
		
	}
}
/* *************************************** 
 *			 ModifyRegistry.cs
 * ---------------------------------------
 *         a very simple class 
 *    to read, write, delete and count
 *       registry values with C#
 * ---------------------------------------
 *      if you improve this code 
 *   please email me your improvement!
 * ---------------------------------------
 *         by Francesco Natali
 *        - fn.varie@libero.it -
 * ***************************************/

using System;
// it's required for reading/writing into the registry:
using Microsoft.Win32;      
// and for the MessageBox function:
using System.Windows.Forms;

namespace Utilitaires
{
	/// <summary>
	/// An useful class to read/write/delete/count registry keys
	/// </summary>
	public class ModifyRegistry
	{
		private bool showError = false;
		/// <summary>
		/// A property to show or hide error messages 
		/// (default = false)
		/// </summary>
		public bool ShowError
		{
			get { return showError; }
			set	{ showError = value; }

          
		}

		private string subKey = "SOFTWARE\\" + Application.ProductName.ToUpper();
		/// <summary>
		/// A property to set the SubKey value
		/// (default = "SOFTWARE\\" + Application.ProductName.ToUpper())
		/// </summary>
		public string SubKey
		{
			get { return subKey; }
			set	{ subKey = value; }
		}

		private RegistryKey baseRegistryKey = Registry.LocalMachine;
		/// <summary>
		/// A property to set the BaseRegistryKey value.
		/// (default = Registry.LocalMachine)
		/// </summary>
		public RegistryKey BaseRegistryKey
		{
			get { return baseRegistryKey; }
			set	{ baseRegistryKey = value; }
		}

		/* **************************************************************************
		 * **************************************************************************/

		/// <summary>
		/// To read a registry key.
		/// input: KeyName (string)
		/// output: value (string) 
		/// </summary>
        public object Read(string KeyName)
		{
			// Opening the registry key
			RegistryKey rk = baseRegistryKey ;
			// Open a subKey as read-only
			RegistryKey sk1 = rk.OpenSubKey(subKey);
			// If the RegistrySubKey doesn't exist -> (null)
			if ( sk1 == null )
			{
				return null;
			}
			else
			{
				try 
				{
					// If the RegistryKey exists I get its value
					// or null is returned.
					return sk1.GetValue(KeyName);
				}
				catch (Exception e)
				{
					// AAAAAAAAAAARGH, an error!
					ShowErrorMessage(e, "Reading registry " + KeyName);
					return null;
				}
			}

		}

        public string ReadString(string KeyName)
        {
            // Opening the registry key
            RegistryKey rk = baseRegistryKey;
            // Open a subKey as read-only
            RegistryKey sk1 = rk.OpenSubKey(subKey);
            // If the RegistrySubKey doesn't exist -> (null)
            if (sk1 == null)
            {
                return null;
            }
            else
            {
                try
                {
                   if (sk1.GetValueKind(KeyName.ToUpper())==RegistryValueKind.String)
                   {
                       return (string)sk1.GetValue(KeyName);
                   }
                }
                catch (Exception e)
                {
                    // AAAAAAAAAAARGH, an error!
                    ShowErrorMessage(e, "Reading registry " + KeyName);
                    return null;
                }
            }

            return null;
        }

        public Int32 ReadInt32(string KeyName)
        {
            // Opening the registry key
            RegistryKey rk = baseRegistryKey;
            // Open a subKey as read-only
            RegistryKey sk1 = rk.OpenSubKey(subKey);
            // If the RegistrySubKey doesn't exist -> (null)
            if (sk1 == null)
            {
                return 0;
            }
            else
            {
                try
                {
                    if (sk1.GetValueKind(KeyName.ToUpper()) == RegistryValueKind.DWord)
                    {
                        return (Int32) sk1.GetValue(KeyName);
                    }
                }
                catch (Exception e)
                {
                    // AAAAAAAAAAARGH, an error!
                    ShowErrorMessage(e, "Reading registry " + KeyName);
                    return 0;
                }
            }
            return 0;
        }

        public byte[] ReadBinary(string KeyName)
        {
            // Opening the registry key
            RegistryKey rk = baseRegistryKey;
            // Open a subKey as read-only
            RegistryKey sk1 = rk.OpenSubKey(subKey);
            // If the RegistrySubKey doesn't exist -> (null)
            if (sk1 == null)
            {
                return null;
            }
            else
            {
                try
                {
                    if (sk1.GetValueKind(KeyName.ToUpper()) == RegistryValueKind.Binary)
                    {
                        return (byte[])sk1.GetValue(KeyName);
                    }
                }
                catch (Exception e)
                {
                    // AAAAAAAAAAARGH, an error!
                    ShowErrorMessage(e, "Reading registry " + KeyName);
                    return null;
                }
            }
            return null;
        }

		/* **************************************************************************
		 * **************************************************************************/

		/// <summary>
		/// To write into a registry key.
		/// input: KeyName (string) , Value (object)
		/// output: true or false 
		/// </summary>
		public bool Write(string KeyName, object Value)
		{
			try
			{

                  
				// Setting
				RegistryKey rk = baseRegistryKey ;
				// I have to use CreateSubKey 
				// (create or open it if already exits), 
				// 'cause OpenSubKey open a subKey as read-only
				RegistryKey sk1 = rk.CreateSubKey(subKey);
				// Save the value
				sk1.SetValue(KeyName, Value);

				return true;
			}
			catch (Exception e)
			{
				// AAAAAAAAAAARGH, an error!
				ShowErrorMessage(e, "Writing registry " + KeyName);
				return false;
			}
		}

		/* **************************************************************************
		 * **************************************************************************/

		/// <summary>
		/// To delete a registry key.
		/// input: KeyName (string)
		/// output: true or false 
		/// </summary>
		public bool DeleteKey(string KeyName)
		{
			try
			{
				// Setting
				RegistryKey rk = baseRegistryKey ;
				RegistryKey sk1 = rk.CreateSubKey(subKey);
				// If the RegistrySubKey doesn't exists -> (true)
				if ( sk1 == null )
					return true;
				else
					sk1.DeleteValue(KeyName);

				return true;
			}
			catch (Exception e)
			{
				// AAAAAAAAAAARGH, an error!
				ShowErrorMessage(e, "Deleting SubKey " + subKey);
				return false;
			}
		}

		/* **************************************************************************
		 * **************************************************************************/

		/// <summary>
		/// To delete a sub key and any child.
		/// input: void
		/// output: true or false 
		/// </summary>
		public bool DeleteSubKeyTree()
		{
			try
			{
				// Setting
				RegistryKey rk = baseRegistryKey ;
				RegistryKey sk1 = rk.OpenSubKey(subKey);
				// If the RegistryKey exists, I delete it
				if ( sk1 != null )
					rk.DeleteSubKeyTree(subKey);

				return true;
			}
			catch (Exception e)
			{
				// AAAAAAAAAAARGH, an error!
				ShowErrorMessage(e, "Deleting SubKey " + subKey);
				return false;
			}
		}

		/* **************************************************************************
		 * **************************************************************************/

		/// <summary>
		/// Retrive the count of subkeys at the current key.
		/// input: void
		/// output: number of subkeys
		/// </summary>
		public int SubKeyCount()
		{
			try
			{
				// Setting
				RegistryKey rk = baseRegistryKey ;
				RegistryKey sk1 = rk.OpenSubKey(subKey);
				// If the RegistryKey exists...
				if ( sk1 != null )
					return sk1.SubKeyCount;
                    
				else
					return 0; 
			}
			catch (Exception e)
			{
				// AAAAAAAAAAARGH, an error!
				ShowErrorMessage(e, "Retriving subkeys of " + subKey);
				return 0;
			}
		}

        public string[] SubKeyNames()
        {
            try
            {
                // Setting
                RegistryKey rk = baseRegistryKey;
                RegistryKey sk1 = rk.OpenSubKey(subKey);
                // If the RegistryKey exists...
                if (sk1 != null)
                    return sk1.GetSubKeyNames();
                else
                    return null;
            }
            catch (Exception e)
            {
                // AAAAAAAAAAARGH, an error!
                ShowErrorMessage(e, "Retriving subkeys of " + subKey);
                return null;
            }
        }

		/* **************************************************************************
		 * **************************************************************************/

		/// <summary>
		/// Retrive the count of values in the key.
		/// input: void
		/// output: number of keys
		/// </summary>
		public int ValueCount()
		{
			try
			{
				// Setting
				RegistryKey rk = baseRegistryKey ;
				RegistryKey sk1 = rk.OpenSubKey(subKey);
				// If the RegistryKey exists...
				if ( sk1 != null )
					return sk1.ValueCount;
				else
					return 0; 
			}
			catch (Exception e)
			{
				// AAAAAAAAAAARGH, an error!
				ShowErrorMessage(e, "Retriving keys of " + subKey);
				return 0;
			}
		}

        public string[] ValueNames()
        {
            try
            {
                // Setting
                RegistryKey rk = baseRegistryKey;
                RegistryKey sk1 = rk.OpenSubKey(subKey);
                // If the RegistryKey exists...
                if (sk1 != null)
                    return sk1.GetValueNames();
                else
                    return null;
            }
            catch (Exception e)
            {
                // AAAAAAAAAAARGH, an error!
                ShowErrorMessage(e, "Retriving keys of " + subKey);
                return null;
            }
        }



		/* **************************************************************************
		 * **************************************************************************/
		
		private void ShowErrorMessage(Exception e, string Title)
		{
			if (showError == true)
				MessageBox.Show(e.Message,
								Title
								,MessageBoxButtons.OK
								,MessageBoxIcon.Error);
		}
	}
}
using System.Threading;



namespace Utilitaires
{
    class SingleInstanceApp : System.IDisposable

    {
        // Mutex
        Mutex _siMutex;
        bool _siMutexOwned;

        // Constructeur
        public SingleInstanceApp(string name)
        {
            _siMutex = new Mutex(false, name);
            _siMutexOwned = false;
        }

        // Application déjà lancée ?
        public bool IsRunning()
        {
            // Acquisition du mutex.
            // Si _siMutexOwned vaut true, l'application acquiert le mutex car il est "libre"
            // Sinon le mutex a déjà été acquis lors du lancement d'une instance précédente
            _siMutexOwned = _siMutex.WaitOne(0, true);
            return !(_siMutexOwned);
        }

        // Membre de IDisposable
        public void Dispose()
        {
            // Libération du mutex si il a été acquis
            if (_siMutexOwned)
                _siMutex.ReleaseMutex();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace Utilitaires
{
    class User32
    {

        [DllImport("USER32.DLL")]
        private static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        private static extern int GetWindowThreadProcessId(IntPtr hWnd, ref int pptt);

        static public string GetForegroundApp()
        {

            Process tmpProc;
            int nThisProcessID = 0;
            try
            {
                GetWindowThreadProcessId(GetForegroundWindow(), ref nThisProcessID);
                tmpProc = Process.GetProcessById(nThisProcessID);
                if (tmpProc != null)
                {
                   
                    return tmpProc.MainModule.ModuleName.ToUpper();
                }
            }
            catch
            {
                Debug.WriteLine("Error GetForegroundApp");
            }
            return null;
        }


    }
}
#include "RBC9-SpaceNav.h"

static UCHAR My_hid_report_descriptor_base[] = {


	/* joystick */
	0x05, 0x01,                 /* Usage Page(Generic Desktop) */
	0x09, 0x04,                 /* Usage(Joystick) */
	0xa1, 0x01,                 /* Collection(Application) */

	0x85, REPORT_ID_JOY,                 /*   Report ID() */

	/* x, y */
	0x05, 0x01,                 /*   Usage Page(Generic Desktop) */
	0x09, 0x01,                 /*   Usage(Pointer) */

	0xa1, 0x00,                 /*   Collection(Physical) */
	0x15, 0x00,                 /*     Logical Minimum(00) */
	//	0x26, 0x20, 0x03,           /*     Logical Maximum(400) */
	0x26, 0xD0, 0x02,           /*     Logical Maximum(2*360) */
	0x75, 0x10,                 /*     Report Size(16) */
	0x95, 0x02,                 /*     Report Count(2) */
	0x05, 0x01,                 /*     Usage Page(Generic Desktop) */
	0x09, 0x30,                 /*     Usage(X) */
	0x09, 0x31,                 /*     Usage(Y) */
	0x81, 0x02,                 /*     Input(Variable, Absolute) */
	0xc0,                       /*   End Collection */

	/* z */
	0x15, 0x00,                 /*     Logical Minimum(00) */
	0x26, 0xD0, 0x02,           /*     Logical Maximum(2*360) */
	0x75, 0x10,                 /*   Report Size(16) */
	0x95, 0x01,                 /*   Report Count(1) */
	0x05, 0x01,                 /*   Usage Page(Generic Desktop) */
	0x09, 0x32,                 /*   Usage(Z) */
	0x81, 0x02,                 /*   Input(Variable, Absolute) */

	/* rx, ry */
	0x05, 0x01,                 /*   Usage Page(Generic Desktop) */
	0x09, 0x01,                 /*   Usage(Pointer) */
	0xa1, 0x00,                 /*   Collection(Physical) */
	0x15, 0x00,                 /*     Logical Minimum(00) */
	0x26, 0xD0, 0x02,           /*     Logical Maximum(2*360) */
	0x75, 0x10,                 /*     Report Size(16) */
	0x95, 0x02,                 /*     Report Count(2) */
	0x05, 0x01,                 /*     Usage Page(Generic Desktop) */
	0x09, 0x33,                 /*     Usage(Rx) */
	0x09, 0x34,                 /*     Usage(Ry) */
	0x81, 0x02,                 /*     Input(Variable, Absolute) */
	0xc0,                       /*   End Collection */

	/* rz */
	0x15, 0x00,                 /*     Logical Minimum(00) */
	0x26, 0xD0, 0x02,           /*     Logical Maximum(2*360) */
	0x75, 0x10,                 /*   Report Size(16) */
	0x95, 0x01,                 /*   Report Count(1) */
	0x05, 0x01,                 /*   Usage Page(Generic Desktop) */
	0x09, 0x35,                 /*   Usage(Rz) */
	0x81, 0x02,                 /*   Input(Variable, Absolute) */

	/* slider */
	0x75, 0x10,                 /*   Report Size(16) */
	0x95, 0x01,                 /*   Report Count(1) */
	0x15, 0x00,                 /*     Logical Minimum(00) */
	0x26, 0xD0, 0x02,           /*     Logical Maximum(2*360) */
	0x05, 0x01,                 /*   Usage Page(Generic Desktop) */
	0x09, 0x36,                 /*   Usage(Slider) */
	0x81, 0x02,                 /*   Input(Variable, Absolute) */

	/* slider Bis */
	0x75, 0x10,                 /*   Report Size(16) */
	0x95, 0x01,                 /*   Report Count(1) */
	0x15, 0x00,                 /*     Logical Minimum(00) */
	0x26, 0xD0, 0x02,           /*     Logical Maximum(2*360) */
	0x05, 0x01,                 /*   Usage Page(Generic Desktop) */
	0x09, 0x36,                 /*   Usage(Slider) */
	0x81, 0x02,                 /*   Input(Variable, Absolute) */

	/* throttle */
	//0x75, 0x10,                 /*   Report Size(16) */
//	0x95, 0x01,                 /*   Report Count(1) */
//	0x15, 0x00,                 /*     Logical Minimum(00) */
//	0x26, 0xD0, 0x02,           /*     Logical Maximum(2*360) */
//	0x05, 0x02,                 /*   Usage Page(Simulation) */
//	0x09, 0xbb,                 /*   Usage(Throttle) */
//	0x81, 0x02,                 /*   Input(Variable, Absolute) */



	/* hat switch 1 */
	0x75, 0x04,                 /*   Report Size(4) */
	0x95, 0x01,                 /*   Report Count(1) */
	0x15, 0x00,                 /*   Logical Minimum(0x00) */
	0x25, 0x07,                 /*   Logical Maximum(0x07) */
	0x35, 0x00,                 /*   Physical Minimum(0x00) */
	0x46, 0x3b, 0x01,           /*   Physical Maximum(0x013b) */
	0x65, 0x14,                 /*   Unit(Degree) */
	0x05, 0x01,                 /*   Usage Page(Generic Desktop) */
	0x09, 0x39,                 /*   Usage(Hat Switch) */
	0x81, 0x42,                 /*   Input(Variable, Absolute, Null State) */

	/*!
	4 bits pour aligner
	*/
	0x75, 0x04,					//     REPORT_SIZE (4)
	0x95, 0x01,					//     REPORT_COUNT (1)
	0x81, 0x01,					//     INPUT (Cnst,Ary,Abs)


	/* button x 8 */
	0x75, 0x01,                 /*   Report Size(1) */
	0x95, 0x08,                 /*   Report Count(8) */
	0x15, 0x00,                 /*   Logical Minimum(0x00) */
	0x25, 0x01,                 /*   Logical Maximum(0x01) */
	0x35, 0x00,                 /*   Physical Minimum(0x00) */
	0x45, 0x01,                 /*   Physical Maximum(0x01) */
	0x05, 0x09,                 /*   Usage Page(Button) */
	0x19, 0x01,                 /*   Usage Minimum(Button 1) */
	0x29, 0x08,                 /*   Usage Maximum(Button 8) */
	0x81, 0x02,                 /*   Input(Variable, Absolute) */
	0xc0,                       /* End Collection */

	/* mouse */
	0x05, 0x01,                 /* Usage Page(Generic Desktop) */
	0x09, 0x02,                 /* Usage(Mouse) */
	0xa1, 0x01,                 /* Collection(Application) */

	0x85, REPORT_ID_MOU,                 /*   Report ID() */

	/* x, y */
	0x05, 0x01,                 /*   Usage Page(Generic Desktop) */
	0x09, 0x01,                 /*   Usage(Pointer) */
	0xa1, 0x00,                 /*   Collection(Physical) */
	0x15, 0x81,                 /*     Logical Minimum(-0x7f) */
	0x25, 0x7f,                 /*     Logical Maximum(+0x7f) */
	//0x35, 0xc0,                 /*     Physical Minimum(-0x40) */
	//0x45, 0x40,                 /*     Physical Maximum(+0x40) */
	0x35, 0x00,                 /*   Physical Minimum(0x00) */
	0x45, 0x00,                 /*   Physical Maximum(0x00) */

	0x75, 0x08,                 /*     Report Size(8) */
	0x95, 0x02,                 /*     Report Count(2) */
	0x05, 0x01,                 /*     Usage Page(Generic Desktop) */
	0x09, 0x30,                 /*     Usage(X) */
	0x09, 0x31,                 /*     Usage(Y) */
	0x81, 0x06,                 /*     Input(Variable, Relative) */
	0xc0,                       /*   End Collection */

	/* wheel */
	0x15, 0x81,                 /*   Logical Minimum(-0x7f) */
	0x25, 0x7f,                 /*   Logical Maximum(+0x7f) */
	0x35, 0x00,                 /*   Physical Minimum(0x00) */
	0x45, 0x00,                 /*   Physical Maximum(0x00) */
	0x75, 0x08,                 /*   Report Size(8) */
	0x95, 0x01,                 /*   Report Count(1) */
	0x05, 0x01,                 /*   Usage Page(Generic Desktop) */
	0x09, 0x38,                 /*   Usage(Wheel) */
	0x81, 0x06,                 /*   Input(Variable, Relative) */

	/* button x 5 */
	0x75, 0x01,                 /*   Report Size(1) */
	0x95, 0x05,                 /*   Report Count(5) */
	0x15, 0x00,                 /*   Logical Minimum(0x00) */
	0x25, 0x01,                 /*   Logical Maximum(0x01) */
	0x35, 0x00,                 /*   Physical Minimum(0x00) */
	0x45, 0x01,                 /*   Physical Maximum(0x01) */
	0x05, 0x09,                 /*   Usage Page(Button) */
	0x19, 0x01,                 /*   Usage Minimum(Button 1) */
	0x29, 0x05,                 /*   Usage Maximum(Button 5) */
	0x81, 0x02,                 /*   Input(Variable, Absolute) */

	/* padding (3bits) */
	0x75, 0x01,                 /*   Report Size(1) */
	0x95, 0x03,                 /*   Report Count(3) */
	0x81, 0x01,                 /*   Input(Constant) */

	0xc0 ,                      /* End Collection */



	// keyboard 
	0x05, 0x01,                    // USAGE_PAGE (Generic Desktop)
    0x09, 0x06,                    // USAGE (Keyboard)
    0xa1, 0x01,                    // COLLECTION (Application)

	0x85, REPORT_ID_KEY,		   //   REPORT_ID 

	0x05, 0x07,                    //   USAGE_PAGE (Keyboard)
    0x19, 0xe0,                    //   USAGE_MINIMUM (Keyboard LeftControl)
    0x29, 0xe7,                    //   USAGE_MAXIMUM (Keyboard Right GUI)
    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
    0x25, 0x01,                    //   LOGICAL_MAXIMUM (1)
    0x75, 0x01,                    //   REPORT_SIZE (1)
    0x95, 0x08,                    //   REPORT_COUNT (8)
    0x81, 0x02,                    //   INPUT (Data,Var,Abs)

    0x95, 0x06,                    //   REPORT_COUNT (6)
    0x75, 0x08,                    //   REPORT_SIZE (8)
    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
    0x25, 0x65,                    //   LOGICAL_MAXIMUM (101)
    0x05, 0x07,                    //   USAGE_PAGE (Keyboard)
    0x19, 0x00,                    //   USAGE_MINIMUM (Reserved (no event indicated))
    0x29, 0x65,                    //   USAGE_MAXIMUM (Keyboard Application)
    0x81, 0x00,                    //   INPUT (Data,Ary,Abs)

	0xc0,                          // END_COLLECTION


// Key Special Key

	0x05, 0x0c,                    // USAGE_PAGE (Consumer Devices)
    0x09, 0x01,                    // USAGE (Consumer Control)
    0xa1, 0x01,                    // COLLECTION (Application)
    0x85, REPORT_ID_WWWKEY,        //   REPORT_ID ()
    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
    0x25, 0x01,                    //   LOGICAL_MAXIMUM (1)
    0x75, 0x01,                    //   REPORT_SIZE (1)
    0x95, 0x10,                    //   REPORT_COUNT (16)
    0x09, 0xe2,                    //   USAGE (Mute) 0x01
    0x09, 0xe9,                    //   USAGE (Volume Up) 0x02
    0x09, 0xea,                    //   USAGE (Volume Down) 0x03
    0x09, 0xcd,                    //   USAGE (Play/Pause) 0x04
    0x09, 0xb7,                    //   USAGE (Stop) 0x05
    0x09, 0xb6,                    //   USAGE (Scan Previous Track) 0x06 
    0x09, 0xb5,                    //   USAGE (Scan Next Track) 0x07
    0x0a, 0x8a, 0x01,              //   USAGE (Mail) 0x08 
    0x0a, 0x92, 0x01,              //   USAGE (Calculator) 0x09 
    0x0a, 0x21, 0x02,              //   USAGE (www search) 0x0a
    0x0a, 0x23, 0x02,              //   USAGE (www home) 0x0b
    0x0a, 0x2a, 0x02,              //   USAGE (www favorites) 0x0c
	0x0a, 0x27, 0x02,              //   USAGE (www refresh) 0x0d
	0x0a, 0x26, 0x02,              //   USAGE (www stop) 0x0e
	0x0a, 0x25, 0x02,              //   USAGE (www forward) 0x0f 
	0x0a, 0x24, 0x02,              //   USAGE (www back) 0x10
    0x81, 0x62,                    //   INPUT (Data,Var,Abs,NPrf,Null)

// Ajout pour comm
	/* Output Report Command */
	0xa1, 0x02,                    //   COLLECTION (Logical)
    0x85, REPORT_ID_CMD,           //   REPORT_ID ()
	0x75, 0x08,						/*   Report Size(8) */
	0x95, 0x03,						/*   Report Count(3) */
	0x15, 0x00,						/*   Logical Minimum(0x00) */
	0x26, 0xff, 0x00,				/*   Logical Maximum(0x00ff) */
	0x06, 0x00, 0xff,				/*   Usage Page(Vendor defined) */
	0x09, 0x01,						/*   Usage(Vendor defined 1) */
	0x91, 0x02,						/*   Output(Variable, Absolute) */
    0xc0,                           //   END_COLLECTION

	/* Input Report */
    0xa1, 0x02,						//   COLLECTION (Logical)
    0x85, REPORT_ID_CMD,			//     REPORT_ID ()
  	0x05, 0x01,						//     USAGE_PAGE (Generic Desktop)
	0x09, 0x3A,						//     USAGE (Counted Buffer)
	0x75, 0x08,						//     REPORT_SIZE (8)
	0x95, 0x03,						//     REPORT_COUNT ()
	0x81, 0x02,						//     INPUT (Data,Var,Abs)
	0xc0,							//   END_COLLECTION

    0xc0,                           //               END_COLLECTION

};

static UCHAR My_hid_report_descriptor_Navigator[] = {
		/* Space Nav */

	0x05, 0x01,                    // USAGE_PAGE (Generic Desktop)
    0x09, 0x08,                    // USAGE (Undefined)
    0xa1, 0x01,                    // COLLECTION (Application)

    0xa1, 0x00,                    //   COLLECTION (Physical)
    0x85, 0x01,                    //     REPORT_ID (1)
    0x16, 0x0c, 0xfe,              //     LOGICAL_MINIMUM (-500)
    0x26, 0xf4, 0x01,              //     LOGICAL_MAXIMUM (500)
    0x36, 0x00, 0x80,              //     PHYSICAL_MINIMUM (-32768)
    0x46, 0xff, 0x7f,              //     PHYSICAL_MAXIMUM (32767)
   // 0x09, 0x30,                    //     USAGE (X)
   // 0x09, 0x31,                    //     USAGE (Y)
    0x09, 0x32,                    //     USAGE (Z) ----> tricherie pour ne pas voir ce "joystick"
	0x09, 0x32,                    //     USAGE (Z) ----> tricherie pour ne pas voir ce "joystick"
	0x09, 0x32,                    //     USAGE (Z)
    0x75, 0x10,                    //     REPORT_SIZE (16)
    0x95, 0x03,                    //     REPORT_COUNT (3)
    0x81, 0x06,                    //     INPUT (Data,Var,Rel)
    0xc0,                          //   END_COLLECTION

    0xa1, 0x00,                    //   COLLECTION (Physical)
    0x85, 0x02,                    //     REPORT_ID (2)
    0x09, 0x33,                    //     USAGE (Rx)
    0x09, 0x34,                    //     USAGE (Ry)
    0x09, 0x35,                    //     USAGE (Rz)
    0x75, 0x10,                    //     REPORT_SIZE (16)
    0x95, 0x03,                    //     REPORT_COUNT (3)
    0x81, 0x06,                    //     INPUT (Data,Var,Rel)
    0xc0,                          //   END_COLLECTION

    0xa1, 0x02,                    //   COLLECTION (Logical)
    0x85, 0x03,                    //     REPORT_ID (3)
    0x05, 0x01,                    //     USAGE_PAGE (Generic Desktop)
    0x05, 0x09,                    //     USAGE_PAGE (Button)
    0x19, 0x01,                    //     USAGE_MINIMUM (Button 1)
    0x29, 0x15,                    //     USAGE_MAXIMUM (Button 2)
    0x15, 0x00,                    //     LOGICAL_MINIMUM (0)
    0x25, 0x01,                    //     LOGICAL_MAXIMUM (1)
    0x35, 0x00,                    //     PHYSICAL_MINIMUM (0)
    0x45, 0x01,                    //     PHYSICAL_MAXIMUM (1)
    0x75, 0x01,                    //     REPORT_SIZE (1)
    0x95, 0x15,                    //     REPORT_COUNT (21)
    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
    0x95, 0x03,                    //     REPORT_COUNT (3)
    0x81, 0x03,                    //     INPUT (Cnst,Var,Abs)

    0xc0,                          //   END_COLLECTION

    0xa1, 0x02,                    //   COLLECTION (Logical)
    0x85, 0x04,                    //     REPORT_ID (4)
    0x05, 0x08,                    //     USAGE_PAGE (LEDs)
    0x09, 0x4b,                    //     USAGE (Generic Indicator)
    0x15, 0x00,                    //     LOGICAL_MINIMUM (0)
    0x25, 0x01,                    //     LOGICAL_MAXIMUM (1)
    0x95, 0x01,                    //     REPORT_COUNT (1)
    0x75, 0x01,                    //     REPORT_SIZE (1)
    0x91, 0x02,                    //     OUTPUT (Data,Var,Abs)
    0x95, 0x01,                    //     REPORT_COUNT (1)
    0x75, 0x07,                    //     REPORT_SIZE (7)
    0x91, 0x03,                    //     OUTPUT (Cnst,Var,Abs)
    0xc0,                          //   END_COLLECTION


	/*Dump SpaceNAv */
0x06, 0x00, 0xff, 0x09, 0x01, 0xa1, 0x02, 0x15, 0x80, 0x25, 0x7f, 0x75, 
0x08, 0x09, 0x3a, 0xa1, 0x02, 0x85, 0x05, 0x09, 0x20, 0x95, 0x01, 0xb1, 
0x02, 0xc0, 0xa1, 0x02, 0x85, 0x06, 0x09, 0x21, 0x95, 0x01, 0xb1, 0x02, 
0xc0, 0xa1, 0x02, 0x85, 0x07, 0x09, 0x22, 0x95, 0x01, 0xb1, 0x02, 0xc0, 
0xa1, 0x02, 0x85, 0x08, 0x09, 0x23, 0x95, 0x07, 0xb1, 0x02, 0xc0, 0xa1, 
0x02, 0x85, 0x09, 0x09, 0x24, 0x95, 0x07, 0xb1, 0x02, 0xc0, 0xa1, 0x02, 
0x85, 0x0a, 0x09, 0x25, 0x95, 0x07, 0xb1, 0x02, 0xc0, 0xa1, 0x02, 0x85, 
0x0b, 0x09, 0x26, 0x95, 0x01, 0xb1, 0x02, 0xc0, 0xc0, 0xc0,

};



NTSTATUS RBC9_hid_start(IN PDEVICE_OBJECT pDev_obj)
{
	PDEVICE_EXTENSION	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);


	DBG_ENTER(("%p %d", pDev_obj,sizeof(My_hid_report_descriptor_base)));

	/* initialize hid part */

	pDevExt->Report_Descriptor_Size = sizeof(My_hid_report_descriptor_base)+pDevExt->Size_HID_Report_Space;
	pDevExt->Reset_Input = TRUE;

	RBC9_nav_init(pDev_obj);
	RBC9_nav_led(pDev_obj,TRUE);

	/* start hid worker */
	{
		HANDLE thread;
		NTSTATUS Status;

		KeInitializeEvent(&pDevExt->hid_worker_wakeup_event,SynchronizationEvent, FALSE);

		/* create thread and start */
		pDevExt->hid_worker_thread_obj = NULL;
		Status = PsCreateSystemThread(&thread,
			THREAD_ALL_ACCESS, NULL, NULL, NULL,
			RBC9_hid_worker, pDev_obj);
		if(! NT_SUCCESS(Status)) {
			DBG_LEAVE(("%x: PsCreateSystemThread failed", Status));
			return Status;
		}

		ObReferenceObjectByHandle(thread, THREAD_ALL_ACCESS, NULL, KernelMode,
			&pDevExt->hid_worker_thread_obj, NULL);
	}




	DBG_LEAVE(("STATUS_SUCCESS"));
	return STATUS_SUCCESS;
}

NTSTATUS RBC9_hid_remove(IN PDEVICE_OBJECT pDev_obj)
{
	PDEVICE_EXTENSION	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	DBG_ENTER(("%p", pDev_obj));

	/* wait for hid worker stop */
	if(pDevExt->hid_worker_thread_obj != NULL) {
		KeSetEvent(&pDevExt->hid_worker_wakeup_event, IO_NO_INCREMENT, FALSE);
		KeWaitForSingleObject(pDevExt->hid_worker_thread_obj,
			Executive, KernelMode, FALSE, NULL);

		ObDereferenceObject(pDevExt->hid_worker_thread_obj);
		pDevExt->hid_worker_thread_obj = NULL;
	}

	DBG_LEAVE(("STATUS_SUCCESS"));
	return STATUS_SUCCESS;
}

NTSTATUS RBC9_hid_get_rep_desc(IN PDEVICE_OBJECT pDev_obj, OUT UCHAR *buf, OUT ULONG *size)
{
	
	PDEVICE_EXTENSION	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	DBG_ENTER(("%p, %p, %d, %d", pDev_obj, buf, *size,sizeof(My_hid_report_descriptor_base)));

	if(*size < pDevExt->Report_Descriptor_Size ) {
		DBG_LEAVE(("STATUS_BUFFER_TOO_SMALL"));
		return STATUS_BUFFER_TOO_SMALL;
	}

	RtlCopyMemory(buf, My_hid_report_descriptor_base, sizeof(My_hid_report_descriptor_base) );
	RtlCopyMemory(buf +sizeof(My_hid_report_descriptor_base) , pDevExt->HID_Report_Space, pDevExt->Size_HID_Report_Space );
	*size = pDevExt->Report_Descriptor_Size ;

	DBG_LEAVE(("STATUS_SUCCESS: %u", *size));
	return STATUS_SUCCESS;
}

NTSTATUS RBC9_hid_read_rep(IN PDEVICE_OBJECT pDev_obj, OUT UCHAR *buf, OUT ULONG *size)
{

	PDEVICE_EXTENSION	pDevExt;
	void				*rep_buf;
	ULONG				rep_size, in_type;

	//DBG_ENTER(("%p", pDev_obj));

	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	if(pDevExt->hid_input_changed & INPUT_TYPE_INFO) {
		in_type = INPUT_TYPE_INFO;
		rep_buf = &pDevExt->input_state.Info;
		rep_size = sizeof(pDevExt->input_state.Info);
	} 
	else if(pDevExt->hid_input_changed & INPUT_TYPE_NAV_ID1) {
		in_type = INPUT_TYPE_NAV_ID1;
		rep_buf = &pDevExt->input_state.SpaceNav.Trame[0];
		rep_size = sizeof(pDevExt->input_state.SpaceNav.Trame[0]);
	} 
	else if(pDevExt->hid_input_changed & INPUT_TYPE_NAV_ID2) {
		in_type = INPUT_TYPE_NAV_ID2;
		rep_buf = &pDevExt->input_state.SpaceNav.Trame[1];
		rep_size = sizeof(pDevExt->input_state.SpaceNav.Trame[1]);
	}
	else if(pDevExt->hid_input_changed & INPUT_TYPE_NAV_ID3) {
		in_type = INPUT_TYPE_NAV_ID3;
		rep_buf = &pDevExt->input_state.SpaceNav.Trame[2];
		rep_size = sizeof(pDevExt->input_state.SpaceNav.Trame[2]);
	} 
	else if(pDevExt->hid_input_changed & INPUT_TYPE_JOYSTICK) {
		/* joystick */
		in_type = INPUT_TYPE_JOYSTICK;
		rep_buf = &pDevExt->input_state.joy;
		rep_size = sizeof(pDevExt->input_state.joy);
	} 
	else if(pDevExt->hid_input_changed & INPUT_TYPE_KEYBOARD) {
		/* keyboard */
		in_type = INPUT_TYPE_KEYBOARD;
		rep_buf = &pDevExt->input_state.kbd;
		rep_size = sizeof(pDevExt->input_state.kbd);
	} else if(pDevExt->hid_input_changed & INPUT_TYPE_WWW) {
		/* wwww */
	//	DBG_OUT(("Balance www"));
		in_type = INPUT_TYPE_WWW;
		rep_buf = &pDevExt->input_state.www;
		rep_size = sizeof(pDevExt->input_state.www);
	} else if(pDevExt->hid_input_changed & INPUT_TYPE_MOUSE) {
		/* mouse */
		in_type = INPUT_TYPE_MOUSE;
		rep_buf = &pDevExt->input_state.mou;
		rep_size = sizeof(pDevExt->input_state.mou);
	} else {
		DBG_LEAVE(("STATUS_UNSUCCESSFUL: not changed: %x",
			pDevExt->hid_input_changed));
		return STATUS_UNSUCCESSFUL;
	}
	//DBG_OUT(("input type: %x/%x ",in_type, pDevExt->hid_input_changed));

	if(*size < rep_size) {
		DBG_LEAVE(("STATUS_BUFFER_TOO_SMALL: %d", *size));
		return STATUS_BUFFER_TOO_SMALL;
	}

	/* copy data */
	RtlCopyMemory(buf, rep_buf, rep_size);
	*size = rep_size;

	/* drop changed bit */
	pDevExt->hid_input_changed &= ~in_type;
	//  DBG_OUT(("input type (dropped): %x", pDevExt->hid_input_changed));

	//  DBG_LEAVE(("STATUS_SUCCESS"));
	return STATUS_SUCCESS;
}


NTSTATUS RBC9_hid_write_control(IN PDEVICE_OBJECT pDev_obj, PCONTROLLER_OUTPUT_REPORT out_state,ULONG *raw_size)
{
	NTSTATUS					Status;

	//DBG_ENTER(("%x %x",ReportId,InfoByte));

	switch(out_state->report_id) 
	{
	case 0x04:
		*raw_size=2;
		Status = RBC9_usb_put_control_transfer(pDev_obj, out_state, raw_size,NAV_PACKET_LED);
		break;
	default:
		NAV_PACKET_INIT[2] = out_state->report_id;
		Status = RBC9_usb_put_control_transfer(pDev_obj, out_state, raw_size,NAV_PACKET_INIT);
	}


	//DBG_LEAVE(("%x", Status));

	return Status;
}

NTSTATUS RBC9_hid_write_rep(IN PDEVICE_OBJECT pDev_obj,IN UCHAR *buf, IN ULONG *size, IN UCHAR id)
{
	PDEVICE_EXTENSION			pDevExt;
	CONTROLLER_OUTPUT_REPORT	out_state;
	NTSTATUS					Status;

//	DBG_ENTER(("%p, %p, %u, %u", pDev_obj, buf, *size, id));

	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	Status = STATUS_SUCCESS;

	if(*size > sizeof(out_state)) {
		*size = sizeof(out_state);
	}

	RtlZeroMemory(&out_state, sizeof(out_state));
	RtlCopyMemory(&out_state, buf, *size);

	DBG_OUT(("report_id 0x%x 0x%x", out_state.report_id,out_state.Cmd.command));

	if (out_state.report_id != REPORT_ID_CMD)
	{
		Status = RBC9_hid_write_control(pDev_obj,&out_state,size);
	}
	else
	{
		switch(out_state.Cmd.command) {
		
		case 0x01:
			// ask nav report
			DBG_OUT(("hid_input_changed"));
			pDevExt->hid_input_changed |= (INPUT_TYPE_NAV_ALL | INPUT_TYPE_INFO);
			break;
		case 0x02:
			// Reload layout
			DBG_OUT(("Reset_Input"));
			pDevExt->Reset_Input = TRUE;
			break;

		case 0x04:
			// Led
			DBG_OUT(("RBC9_nav_led"));
			Status = RBC9_nav_led(pDev_obj,(out_state.Cmd.InfoByte !=0) ? TRUE :FALSE);
			break;

		case 0x06:
			// Init
			DBG_OUT(("RBC9_nav_init"));
			Status = RBC9_nav_init(pDev_obj);
			break;

		case 0x07:
			// Init
			DBG_OUT(("RBC9_nav_calibrate"));
			Status = RBC9_nav_calibrate(pDev_obj);
			break;
		
		case 0x08:
			// Switch to profil num
			DBG_OUT(("Profil Num : %d", out_state.Cmd.ProfilNum));
			pDevExt->Profil_Actif = RBC9_Select_Profil(pDev_obj,out_state.Cmd.ProfilNum);
			break;

		case 0xFF:
			// Mode Config
			DBG_OUT(("ModeConfig  : %d",out_state.Cmd.InfoByte));
			pDevExt->ModeConfig = (out_state.Cmd.InfoByte !=0) ? TRUE :FALSE;
			if(!pDevExt->ModeConfig)
			{
				RBC9_SEQ_Special_Action_Fin(pDev_obj);
			}
			break;

		default:
			DBG_OUT(("unknown write command: 0x%x", out_state.Cmd.command));
			break;
		}
	
	}
	//DBG_LEAVE(("%x", Status));
	return Status;

}

NTSTATUS RBC9_nav_led(IN PDEVICE_OBJECT pDev_obj,BOOLEAN Led)
{
	//DBG_ENTER((" LED : %x", Led));
	CONTROLLER_OUTPUT_REPORT	out_state;
	ULONG size;

	out_state.report_id = 4;
	out_state.OriByte[0]=Led ? 1 : 0;
	size = 2;

	return RBC9_hid_write_control(pDev_obj,&out_state,&size);
}

NTSTATUS RBC9_nav_calibrate(IN PDEVICE_OBJECT pDev_obj)
{
	CONTROLLER_OUTPUT_REPORT	out_state;
	ULONG size;

	out_state.report_id = 7;
	out_state.OriByte[0]= 0;
	size = 2;

	return RBC9_hid_write_control(pDev_obj,&out_state,&size);
}

NTSTATUS RBC9_nav_init(IN PDEVICE_OBJECT pDev_obj)
{

	CONTROLLER_OUTPUT_REPORT	out_state;
	ULONG size;

	out_state.report_id = 6;
	out_state.OriByte[0]= 3;
	size = 2;

	return RBC9_hid_write_control(pDev_obj,&out_state,&size);
}


static VOID RBC9_hid_update_from_raw_input(IN PDEVICE_OBJECT pDev_obj)
{
	PDEVICE_EXTENSION		pDevExt;
	CONTROLLER_INPUT_REPORT in_state;
	ULONG					changed_flag;
	ULONGLONG				cur_time;

	//DBG_ENTER(("%p", pDev_obj));

	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	in_state = pDevExt->input_state;

	/* process input data */
	RBC9_process_raw_input(pDev_obj);

	if (pDevExt->ModeConfig)
	{
		if (pDevExt->Led == NULL)
				{
					RBC9_SEQ_Special_Action(pDev_obj);
				}	
	}
	
	if (pDevExt->Led) RBC9_Led_Clignote(pDev_obj);

	/* check state change */
	changed_flag = 0;

	/* Info state */
	if(RtlCompareMemory(&pDevExt->input_state.Info, &in_state.Info,sizeof(in_state.Info)) != sizeof(in_state.Info)) 
	{
		changed_flag |= INPUT_TYPE_INFO;
	}

	/* NAVID1 state */
	if(RtlCompareMemory(&pDevExt->input_state.SpaceNav.Trame[0], &in_state.SpaceNav.Trame[0],sizeof(in_state.SpaceNav.Trame[0])) != sizeof(in_state.SpaceNav.Trame[0])) 
	{
		changed_flag |= INPUT_TYPE_NAV_ID1;
	}

	/* NAVID2 state */
	if(RtlCompareMemory(&pDevExt->input_state.SpaceNav.Trame[1], &in_state.SpaceNav.Trame[1],sizeof(in_state.SpaceNav.Trame[1])) != sizeof(in_state.SpaceNav.Trame[1])) 
	{
		changed_flag |= INPUT_TYPE_NAV_ID2;
	}

	/* NAVID3 state */
	if(RtlCompareMemory(&pDevExt->input_state.SpaceNav.Trame[2], &in_state.SpaceNav.Trame[2],sizeof(in_state.SpaceNav.Trame[2])) != sizeof(in_state.SpaceNav.Trame[2])) 
	{
		changed_flag |= INPUT_TYPE_NAV_ID3;
	}

	/* joystick state */
	if(RtlCompareMemory(&pDevExt->input_state.joy, &in_state.joy,sizeof(in_state.joy)) != sizeof(in_state.joy)) 
	{
		//DBG_OUT(("joystick changed"));
		changed_flag |= INPUT_TYPE_JOYSTICK;
	}

	/* keyboard state */
	if(RtlCompareMemory(&pDevExt->input_state.kbd, &in_state.kbd, sizeof(in_state.kbd)) != sizeof(in_state.kbd)) 
	{
		//DBG_OUT(("keyboard changed"));
		changed_flag |= INPUT_TYPE_KEYBOARD;
	}

	/* www state */
	if(RtlCompareMemory(&pDevExt->input_state.www, &in_state.www, sizeof(in_state.www)) != sizeof(in_state.www)) 
	{
	//	DBG_OUT(("www changed"));
		changed_flag |= INPUT_TYPE_WWW;
	}


	/* mouse state */
	cur_time = KeQueryInterruptTime();

	if(cur_time >= (pDevExt->Mouse.wheel_time  + (pDevExt->Mouse.wheel_wait * 10 * 1000)))
	{
		pDevExt->input_state.mou.wheel = pDevExt->Mouse.wheel_val;
	}
	else
	{
		pDevExt->input_state.mou.wheel=0;
	}

	if(pDevExt->input_state.mou.x != 0 ||
		pDevExt->input_state.mou.y != 0 ||
		pDevExt->input_state.mou.wheel != 0 ||
		RtlCompareMemory(&pDevExt->input_state.mou.button, &in_state.mou.button,sizeof(in_state.mou.button)) != sizeof(in_state.mou.button)) 
	{
		if(cur_time >= pDevExt->Mouse.next_time) { /* only for each 10ms */
			//DBG_OUT(("mouse changed"));
			changed_flag |= INPUT_TYPE_MOUSE;
			pDevExt->Mouse.next_time = cur_time + 10 * 10 * 1000;
			if (pDevExt->input_state.mou.wheel != 0)
			{
				pDevExt->Mouse.wheel_time = cur_time;
			}
		}
	}

	/* save current state */
	pDevExt->hid_input_changed |= changed_flag;

	/* notify to ioctl layer */
	if(pDevExt->hid_input_changed) {
		RBC9_notify_input_report_change(pDev_obj);
	}


	//DBG_LEAVE(("void"));
}


static VOID RBC9_hid_generate_raw_output(PCONTROLLER_OUTPUT_REPORT out_state,PRAW_OUTPUT raw_out)
{
	int i;

	DBG_ENTER(("%p, %p", out_state, raw_out));

	//raw_out->ReportId = 4;
	//raw_out->OutPut[0] = out_state->Value[0];

	DBG_LEAVE(("void"));
}

#pragma warning(disable : 4996)
#pragma PAGEDCODE
static VOID RBC9_hid_worker(IN PVOID ctxt)
{
	PDEVICE_OBJECT		pDev_obj;
	PDEVICE_EXTENSION	pDevExt;
	LARGE_INTEGER		time;

	DBG_ENTER(("%p", ctxt));

	pDev_obj = (PDEVICE_OBJECT)ctxt;
	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	KeSetPriorityThread(KeGetCurrentThread(), LOW_REALTIME_PRIORITY);

	while(pDevExt->Pnp_State == DEVICE_STATE_STARTED) {
		if(pDevExt->Reset_Input) 
		{
			/* reload setting */
			RBC9_InitState(pDev_obj);
			pDevExt->Reset_Input = FALSE;
		}

		KeResetEvent(&pDevExt->hid_worker_wakeup_event);

		/* update input report data */
		RBC9_hid_update_from_raw_input(pDev_obj);

		/* wait for wakeup or 10ms */
		time = RtlConvertLongToLargeInteger(-10 * 1000 * 10);
		KeWaitForSingleObject(&pDevExt->hid_worker_wakeup_event, Executive,	KernelMode, FALSE, &time);

		//DBG_OUT(("RBC9_hid_worker ReportId %x",pDevExt->hwInData.ReportId));
	}

	DBG_OUT(("already stop/removed"));
	RBC9_notify_input_report_stop(pDev_obj);

	DBG_LEAVE(("STATUS_SUCCESS"));
	PsTerminateSystemThread(STATUS_SUCCESS);
}
#include "RBC9-SpaceNav.h"

#pragma PAGEDCODE
static VOID RBC9_cancel_read_report(IN PDEVICE_OBJECT pDev_obj, IN PIRP pIrp)
{
    PDEVICE_EXTENSION		pDevExt;
    KIRQL irql;

 //   DBG_ENTER(("%p, %p", pDev_obj, pIrp));

    pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

    IoReleaseCancelSpinLock(pIrp->CancelIrql);

    KeAcquireSpinLock(&pDevExt->Pending_Read_irp_Lock, &irql);
    RemoveEntryList(&pIrp->Tail.Overlay.ListEntry);
    InitializeListHead(&pIrp->Tail.Overlay.ListEntry);
    KeReleaseSpinLock(&pDevExt->Pending_Read_irp_Lock, irql);

    RBC9_COMPLETE_REQUEST(pIrp, 0, STATUS_CANCELLED, IO_NO_INCREMENT);

  //  DBG_LEAVE(("void"));
}

#pragma LOCKEDCODE

__inline static PIRP RBC9_dequeue_Pending_Read_irp(IN PDEVICE_OBJECT pDev_obj)
{
    PDEVICE_EXTENSION		pDevExt;
    PIRP					pIrp;
    PLIST_ENTRY				entry;
    KIRQL					irql;

   // DBG_ENTER(("%p", pDev_obj));

    pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

    do {
        if(IsListEmpty(&pDevExt->Pending_Read_irp)) {
           // DBG_LEAVE(("NULL: Pending_Read_irp is empty"));
            return NULL;
        }

        KeAcquireSpinLock(&pDevExt->Pending_Read_irp_Lock, &irql);
        entry = RemoveHeadList(&pDevExt->Pending_Read_irp);
        InitializeListHead(entry);
        KeReleaseSpinLock(&pDevExt->Pending_Read_irp_Lock, irql);

        pIrp = CONTAINING_RECORD(entry, IRP, Tail.Overlay.ListEntry);
        if(IoSetCancelRoutine(pIrp, NULL) == NULL) {
            DBG_OUT(("already cancelling: %p", pIrp));
            pIrp = NULL;
        }
    } while(pIrp == NULL);

   // DBG_LEAVE(("%p", pIrp));
    return pIrp;
}
__inline static void RBC9_enqueue_Pending_Read_irp(IN PDEVICE_OBJECT pDev_obj, IN PIRP pIrp)
{
    PDEVICE_EXTENSION		pDevExt;
    KIRQL irql;

  //  DBG_ENTER(("%p, %p", pDev_obj, pIrp));

    pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

    InitializeListHead(&pIrp->Tail.Overlay.ListEntry);
    IoSetCancelRoutine(pIrp, RBC9_cancel_read_report);

    KeAcquireSpinLock(&pDevExt->Pending_Read_irp_Lock, &irql);
    InsertTailList(&pDevExt->Pending_Read_irp, &pIrp->Tail.Overlay.ListEntry);
    KeReleaseSpinLock(&pDevExt->Pending_Read_irp_Lock, irql);

  //  DBG_LEAVE(("void"));
}

__inline static NTSTATUS RBC9_complete_read_report(IN PDEVICE_OBJECT pDev_obj, IN PIRP pIrp)
{
    PDEVICE_EXTENSION		pDevExt;
    PIO_STACK_LOCATION		irp_sp;
    ULONG					size;
    UCHAR					*buf;
    NTSTATUS				Status;

  //  DBG_ENTER(("%p, %p", pDev_obj, pIrp));

    pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

    irp_sp = IoGetCurrentIrpStackLocation(pIrp);

    size = irp_sp->Parameters.DeviceIoControl.OutputBufferLength;
    buf = pIrp->UserBuffer;

    Status = RBC9_hid_read_rep(pDev_obj, buf, &size);
    if(! NT_SUCCESS(Status)) {
        RBC9_COMPLETE_REQUEST(pIrp, 0, Status, IO_NO_INCREMENT);

        DBG_LEAVE(("%x", Status));
        return Status;
    }

    RBC9_COMPLETE_REQUEST(pIrp, size, STATUS_SUCCESS, IO_NO_INCREMENT);

 //   DBG_LEAVE(("STATUS_SUCCESS"));
    return STATUS_SUCCESS;
}


NTSTATUS RBC9_ioctl_get_dev_desc(IN PDEVICE_OBJECT pDev_obj, IN PIRP pIrp)
{
	PDEVICE_EXTENSION		pDevExt;
    PIO_STACK_LOCATION		irp_sp;
    PHID_DESCRIPTOR			hid_desc;

    DBG_ENTER(("%p, %p", pDev_obj, pIrp));

    pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
    irp_sp = IoGetCurrentIrpStackLocation(pIrp);
    hid_desc = (PHID_DESCRIPTOR)pIrp->UserBuffer;

    if(irp_sp->Parameters.DeviceIoControl.OutputBufferLength <
       sizeof(*hid_desc)) {
        RBC9_COMPLETE_REQUEST(pIrp, 0, STATUS_BUFFER_TOO_SMALL, IO_NO_INCREMENT);

        DBG_LEAVE(("STATUS_BUFFER_TOO_SMALL"));
        return STATUS_BUFFER_TOO_SMALL;
    }

    RtlZeroMemory(hid_desc, sizeof(*hid_desc));
    hid_desc->bLength = sizeof(*hid_desc);
    hid_desc->bDescriptorType = HID_HID_DESCRIPTOR_TYPE;
    hid_desc->bcdHID = HID_REVISION;
    hid_desc->bCountry = 0;
    hid_desc->bNumDescriptors = 1;
    hid_desc->DescriptorList[0].bReportType = HID_REPORT_DESCRIPTOR_TYPE;
    hid_desc->DescriptorList[0].wReportLength = pDevExt->Report_Descriptor_Size;
//	DBG_OUT(("pDevExt->Report_Descriptor_Size %d",pDevExt->Report_Descriptor_Size));

    RBC9_COMPLETE_REQUEST(pIrp, sizeof(*hid_desc), STATUS_SUCCESS, IO_NO_INCREMENT);

    DBG_LEAVE(("STATUS_SUCCESS"));
    return STATUS_SUCCESS;
}

NTSTATUS RBC9_ioctl_get_dev_attr(IN PDEVICE_OBJECT pDev_obj,	IN PIRP pIrp)
{
	PDEVICE_EXTENSION		pDevExt;
    PIO_STACK_LOCATION irp_sp;
    PHID_DEVICE_ATTRIBUTES hid_attr;
    
    DBG_ENTER(("%p, %p", pDev_obj, pIrp));

       pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
    irp_sp = IoGetCurrentIrpStackLocation(pIrp);
    hid_attr = (PHID_DEVICE_ATTRIBUTES)pIrp->UserBuffer;

    if(irp_sp->Parameters.DeviceIoControl.OutputBufferLength <
       sizeof(*hid_attr)) {
        RBC9_COMPLETE_REQUEST(pIrp, 0, STATUS_BUFFER_TOO_SMALL, IO_NO_INCREMENT);

        DBG_LEAVE(("%u < %d",
                   irp_sp->Parameters.DeviceIoControl.OutputBufferLength,
                   sizeof(*hid_attr)));
        return STATUS_BUFFER_TOO_SMALL;
    }

    hid_attr->Size = sizeof(*hid_attr);
    hid_attr->VendorID = pDevExt->DeviceDescriptor.idVendor;
    hid_attr->ProductID = pDevExt->DeviceDescriptor.idProduct;
    hid_attr->VersionNumber = pDevExt->DeviceDescriptor.bcdDevice;

//DBG_OUT(("VendorId and Product Id to test !!!!!!!!!!!!!!!!!!!!"));
//	hid_attr->VendorID = 0x0800;
 //  hid_attr->ProductID = 0x0777;
 //   hid_attr->VersionNumber = 0x0666;
	

    RBC9_COMPLETE_REQUEST(pIrp, sizeof(*hid_attr), STATUS_SUCCESS, IO_NO_INCREMENT);

   DBG_LEAVE(("STATUS_SUCCESS"));
    return STATUS_SUCCESS;
}

NTSTATUS RBC9_ioctl_get_rep_desc(IN PDEVICE_OBJECT pDev_obj,	IN PIRP pIrp)
{
	PIO_STACK_LOCATION irp_sp;
    ULONG size;
    UCHAR *buf;
    NTSTATUS Status;

    DBG_ENTER(("%p, %p", pDev_obj, pIrp));

    irp_sp = IoGetCurrentIrpStackLocation(pIrp);

    size = irp_sp->Parameters.DeviceIoControl.OutputBufferLength;
    buf = pIrp->UserBuffer;

    Status = RBC9_hid_get_rep_desc(pDev_obj, buf, &size);
	
    if(! NT_SUCCESS(Status)) {
        RBC9_COMPLETE_REQUEST(pIrp, 0, Status, IO_NO_INCREMENT);

        DBG_LEAVE(("%x", Status));
        return Status;
    }

    RBC9_COMPLETE_REQUEST(pIrp, size, STATUS_SUCCESS, IO_NO_INCREMENT);

    DBG_LEAVE(("STATUS_SUCCESS"));
    return STATUS_SUCCESS;
}

NTSTATUS RBC9_ioctl_read_rep(IN PDEVICE_OBJECT pDev_obj,	IN PIRP pIrp)
{
	PDEVICE_EXTENSION		pDevExt;

  //  DBG_ENTER(("%p, %p", pDev_obj, pIrp));

    pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	
    if(pDevExt->Pnp_State != DEVICE_STATE_STARTED) {
        /* device is not started */
        RBC9_COMPLETE_REQUEST(pIrp, 0, STATUS_DEVICE_NOT_CONNECTED, IO_NO_INCREMENT);

        DBG_LEAVE(("STATUS_DEVICE_NOT_CONNECTED: device is not started"));
		
		RBC9_device_start(pDev_obj);

        return STATUS_DEVICE_NOT_CONNECTED;
    }
	

    /* enqueue current irp */
    IoMarkIrpPending(pIrp);
    RBC9_enqueue_Pending_Read_irp(pDev_obj, pIrp);
	
	/* indicate to complete request */
    KeSetEvent(&pDevExt->hid_worker_wakeup_event, IO_NO_INCREMENT, FALSE);

  //  DBG_LEAVE(("STATUS_PENDING"));
    return STATUS_PENDING;
}

NTSTATUS RBC9_ioctl_write_rep(IN PDEVICE_OBJECT pDev_obj,	IN PIRP pIrp)
{
	PHID_XFER_PACKET xfer_packet;
    ULONG size;
    UCHAR *buf;
    UCHAR id;
    NTSTATUS Status;

   // DBG_ENTER(("%p, %p", pDev_obj, pIrp));

    xfer_packet = (PHID_XFER_PACKET)pIrp->UserBuffer;
    size = xfer_packet->reportBufferLen;
    buf = xfer_packet->reportBuffer;
    id = xfer_packet->reportId;

    Status = RBC9_hid_write_rep(pDev_obj, buf, &size, id);
    if(! NT_SUCCESS(Status)) {
        RBC9_COMPLETE_REQUEST(pIrp, 0, Status, IO_NO_INCREMENT);

        DBG_LEAVE(("%x", Status));
        return Status;
    }

    RBC9_COMPLETE_REQUEST(pIrp, size, STATUS_SUCCESS, IO_NO_INCREMENT);

  //  DBG_LEAVE(("STATUS_SUCCESS"));
    return STATUS_SUCCESS;
}


VOID RBC9_notify_input_report_change(IN PDEVICE_OBJECT pDev_obj)
{
    PDEVICE_EXTENSION		pDevExt;
    PIRP					pIrp;
    NTSTATUS				Status;

   // DBG_ENTER(("%p", pDev_obj));

    pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

    while(pDevExt->hid_input_changed) {
        pIrp = RBC9_dequeue_Pending_Read_irp(pDev_obj);
        if(pIrp == NULL) {
           // DBG_OUT(("no more irp exist"));
            break;
        }

        Status = RBC9_complete_read_report(pDev_obj, pIrp);
        if(! NT_SUCCESS(Status)) {
            DBG_OUT(("%x: complete_read_report failed",Status));
            break;
        }
    }

   // DBG_LEAVE(("void"));
}

VOID RBC9_notify_input_report_stop(IN PDEVICE_OBJECT pDev_obj)
{
	PDEVICE_EXTENSION		pDevExt;
    PIRP					pIrp;

   // DBG_ENTER(("%p", pDev_obj));

    pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

    /* cancel all requests */
    while(pIrp = RBC9_dequeue_Pending_Read_irp(pDev_obj),
          pIrp != NULL) {
       // DBG_OUT(("cancel irp: %p", pIrp));
        RBC9_COMPLETE_REQUEST(pIrp, 0, STATUS_CANCELLED, IO_NO_INCREMENT);
    }

   // DBG_LEAVE(("void"));
}



#include "RBC9-SpaceNav.h"


#pragma warning(disable : 4996)

VOID RBC9_SEQ_Init_HID(IN PDEVICE_OBJECT pDev_obj)
{
	RBC9_Led_Queue_Delete(pDev_obj);
	RBC9_Led_Queue_Add(pDev_obj,2000,500,250);
	RBC9_Led_Queue_Add(pDev_obj,2000,300,150);
	RBC9_Led_Queue_Add(pDev_obj,2000,200,100);

}

VOID RBC9_SEQ_Special_Action(IN PDEVICE_OBJECT pDev_obj)
{
	RBC9_Led_Queue_Delete(pDev_obj);
	RBC9_Led_Queue_Add(pDev_obj,5000,100,500);
}

VOID RBC9_SEQ_Special_Action_Fin(IN PDEVICE_OBJECT pDev_obj)
{
	RBC9_Led_Queue_Delete(pDev_obj);
	RBC9_Led_Queue_Add(pDev_obj,2000,50,100);
}

VOID RBC9_SEQ_Change_Profil(IN PDEVICE_OBJECT pDev_obj)
{
	RBC9_Led_Queue_Delete(pDev_obj);
	RBC9_Led_Queue_Add(pDev_obj,1000,50,10);

}


VOID RBC9_Led_Clignote(IN PDEVICE_OBJECT pDev_obj)
{
	PDEVICE_EXTENSION		pDevExt;
	ULONGLONG				cur_time;
	PLED_REPEAT				NextLed;

	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	cur_time = KeQueryInterruptTime();

	if(cur_time > pDevExt->Led->next_time)
	{

		//	DBG_ENTER((""));

		if(pDevExt->Led->first_time == 0)
		{
			pDevExt->Led->first_time = cur_time;
		}

		if (pDevExt->Led->first_time + (pDevExt->Led->HowLong * 10 * 1000) < cur_time)
		{
			NextLed = pDevExt->Led->NextLed;

			if(pDevExt->Led->NextLed != NULL)
			{
				pDevExt->Led->NextLed->On = pDevExt->Led->On;
			}

			ExFreePool(pDevExt->Led);

			pDevExt->Led = NextLed;

			//DBG_LEAVE(("Fin de sequence"));
			RBC9_nav_led(pDev_obj,TRUE);
			return;
		}


		pDevExt->Led->On = !pDevExt->Led->On;

		RBC9_nav_led(pDev_obj,pDevExt->Led->On);

		pDevExt->Led->next_time = cur_time + ((pDevExt->Led->On) ? pDevExt->Led->TimeOn:pDevExt->Led->TimeOff) * 10 * 1000;



		//	DBG_LEAVE((""));
	}

}

VOID RBC9_Led_Queue_Delete(IN PDEVICE_OBJECT pDev_obj)
{
	PDEVICE_EXTENSION	pDevExt= GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	PLED_REPEAT			FirstLed;
	PLED_REPEAT			NextLed;

	//DBG_ENTER((""));

	FirstLed=pDevExt->Led;
	pDevExt->Led = NULL;

	while(FirstLed !=NULL)
	{
		NextLed = FirstLed->NextLed;

		//DBG_OUT(("Delete Led"));

		ExFreePool(FirstLed);

		FirstLed = NextLed;

	}

	//DBG_LEAVE((""));
}


VOID RBC9_Led_Queue_Add(IN PDEVICE_OBJECT pDev_obj,int HowLong,int TimeOn,int TimeOff)
{
	PDEVICE_EXTENSION	pDevExt= GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	PLED_REPEAT			NewLed=(PLED_REPEAT)  ExAllocatePool(NonPagedPool, sizeof(LED_REPEAT));

	PLED_REPEAT			NextLed;
	PLED_REPEAT			LastLed;

	//	DBG_ENTER((""));

	if (NewLed == NULL)
	{
		DBG_LEAVE(("ExAllocatePool Error"));
		return;
	}
	RtlZeroMemory(NewLed, sizeof(LED_REPEAT));


	if (pDevExt->Led == NULL)
	{

		pDevExt->Led = NewLed;
	}
	else
	{
		NextLed = pDevExt->Led->NextLed;
		LastLed = pDevExt->Led;

		while (NextLed != NULL)
		{
			LastLed = NextLed;
			NextLed = LastLed->NextLed;
		}

		LastLed->NextLed = NewLed;
	}

	NewLed->On = 0;
	NewLed->first_time = 0;
	NewLed->next_time = 0;
	NewLed->HowLong = HowLong;
	NewLed->TimeOn = TimeOn;
	NewLed->TimeOff = TimeOff;




	//DBG_LEAVE((""));

}#include "RBC9-SpaceNav.h"

#pragma PAGEDCODE
NTSTATUS RBC9_pnp_complete(IN PDEVICE_OBJECT pDev_obj, IN PIRP pIrp,IN PVOID ctxt)
{
	NTSTATUS			Status=STATUS_MORE_PROCESSING_REQUIRED;
	//DBG_ENTER(("%p, %p, %p", pDev_obj, pIrp, ctxt));
	KeSetEvent((PKEVENT)ctxt, IO_NO_INCREMENT, FALSE);

	if(pIrp->PendingReturned) {
		IoMarkIrpPending(pIrp);
	}

	//DBG_LEAVE(("%x", Status));
	return Status;
}

#pragma LOCKEDCODE
NTSTATUS RBC9_pnp_start(IN PDEVICE_OBJECT pDev_obj,	IN PIRP pIrp)
{
	NTSTATUS			Status;
	PDEVICE_EXTENSION	pDevExt;
	KEVENT				start_event;

//	DBG_ENTER(("%p, %p", pDev_obj, pIrp));

	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	/* start lower device */
	KeInitializeEvent(&start_event, NotificationEvent, FALSE);

	IoCopyCurrentIrpStackLocationToNext(pIrp);
	IoSetCompletionRoutine(pIrp, RBC9_pnp_complete, &start_event, TRUE, TRUE, TRUE);

	Status = IoCallDriver(GET_LOWER_DEVICE_OBJECT(pDev_obj), pIrp);
	if(! NT_SUCCESS(Status)) 
	{
		DBG_LEAVE(("%x: IoCallDriver failed", Status));
		RBC9_COMPLETE_REQUEST(pIrp, 0, Status, IO_NO_INCREMENT);
		return Status;
	}

//	DBG_OUT(("waiting start event: %p", &start_event));
	KeWaitForSingleObject(&start_event, Executive, KernelMode, FALSE, NULL);

	Status = pIrp->IoStatus.Status;
	if(! NT_SUCCESS(Status)) 
	{
		DBG_LEAVE(("%x: calling next device failed", Status));
		RBC9_COMPLETE_REQUEST(pIrp, 0, Status, IO_NO_INCREMENT);
		return Status;
	}

	/* start this device */
	Status = RBC9_device_start(pDev_obj);
	if(! NT_SUCCESS(Status)) 
	{
		DBG_LEAVE(("%x: device_start failed", Status));
		RBC9_COMPLETE_REQUEST(pIrp, 0, Status, IO_NO_INCREMENT);
		return Status;
	}

	RBC9_COMPLETE_REQUEST(pIrp, 0, Status, IO_NO_INCREMENT);

//	DBG_LEAVE(("%x", Status));
	return Status;
}

NTSTATUS RBC9_device_start(IN PDEVICE_OBJECT pDev_obj)
{
	NTSTATUS			Status;
	PDEVICE_EXTENSION	pDevExt;

	DBG_ENTER(("%p", pDev_obj));


	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	/* initialize usb */
	Status = RBC9_usb_start(pDev_obj);
	if(! NT_SUCCESS(Status)) {
		DBG_LEAVE(("%x: usb_start failed", Status));
		return Status;
	}

	DBG_LEAVE(("%x", Status));
	return STATUS_SUCCESS;
}

NTSTATUS RBC9_pnp_stop(IN PDEVICE_OBJECT pDev_obj,	IN PIRP pIrp)
{
	NTSTATUS			Status;
	PDEVICE_EXTENSION	pDevExt;

	DBG_ENTER(("%p, %p", pDev_obj, pIrp));

	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	/* stop this device */
	pDevExt->Pnp_State = DEVICE_STATE_STOPPED;

	/* stop lower device */
	IoSkipCurrentIrpStackLocation(pIrp);
	Status = IoCallDriver(GET_LOWER_DEVICE_OBJECT(pDev_obj), pIrp);

	DBG_LEAVE(("%x", Status));

	return Status;
}
NTSTATUS RBC9_pnp_surprise_remove(IN PDEVICE_OBJECT pDev_obj,	IN PIRP pIrp)
{
	NTSTATUS			Status;
	PDEVICE_EXTENSION	pDevExt;

	//DBG_ENTER(("%p, %p", pDev_obj, pIrp));

	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	/* remove this device */
	pDevExt->Pnp_State = DEVICE_STATE_REMOVED;
	RBC9_device_remove(pDev_obj);

	/* remove lower device */
	pIrp->IoStatus.Status = STATUS_SUCCESS;
	IoSkipCurrentIrpStackLocation(pIrp);
	Status = IoCallDriver(GET_LOWER_DEVICE_OBJECT(pDev_obj), pIrp);

//	DBG_LEAVE(("%x", Status));

	return Status;
}
NTSTATUS RBC9_pnp_remove(IN PDEVICE_OBJECT pDev_obj,	IN PIRP pIrp)
{
	NTSTATUS			Status=STATUS_SUCCESS;
	PDEVICE_EXTENSION	pDevExt;

	//DBG_ENTER(("%p, %p", pDev_obj, pIrp));

	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	/* remove this device */
	pDevExt->Pnp_State = DEVICE_STATE_REMOVED;
	RBC9_device_remove(pDev_obj);

	{
		LONG cnt;

		InterlockedDecrement(&pDevExt->RequestCount); /* irp_pnp's req */
		cnt = InterlockedDecrement(&pDevExt->RequestCount); /* device_add's req */
		if(cnt > 0) {
			KeWaitForSingleObject(&pDevExt->Remove_Event,Executive, KernelMode, FALSE, NULL);
		}
	}

	/* remove lower device */
	IoSkipCurrentIrpStackLocation(pIrp);
	IoCallDriver(GET_LOWER_DEVICE_OBJECT(pDev_obj), pIrp);

	//DBG_LEAVE(("%x", Status));

	return Status;
}

NTSTATUS RBC9_device_remove(IN PDEVICE_OBJECT pDev_obj)
{
	NTSTATUS			Status=STATUS_SUCCESS;
	PDEVICE_EXTENSION	pDevExt;

	//DBG_ENTER(("%p", pDev_obj));

	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	/* finalize usb */
	RBC9_usb_remove(pDev_obj);

//	DBG_LEAVE(("%x", Status));
	return STATUS_SUCCESS;
}

NTSTATUS RBC9_pnp_capabilities(IN PDEVICE_OBJECT pDev_obj,	IN PIRP pIrp)
{
	NTSTATUS				Status=STATUS_SUCCESS;
	PIO_STACK_LOCATION		pStack;
	PDEVICE_CAPABILITIES	dev_caps;

	//DBG_ENTER(("%p, %p", pDev_obj, pIrp));

	pStack = IoGetCurrentIrpStackLocation(pIrp);

	dev_caps = pStack->Parameters.DeviceCapabilities.Capabilities;
	dev_caps->LockSupported = FALSE;
	dev_caps->EjectSupported = FALSE;
	dev_caps->Removable = TRUE;
	dev_caps->DockDevice = FALSE;
	dev_caps->UniqueID = FALSE;
	dev_caps->SurpriseRemovalOK = TRUE;
	dev_caps->SystemWake = PowerSystemUnspecified;
	dev_caps->DeviceWake = PowerDeviceUnspecified;

	RBC9_COMPLETE_REQUEST(pIrp, 0, STATUS_SUCCESS, IO_NO_INCREMENT);

	//DBG_LEAVE(("%x", Status));
	return Status;
}
#include "RBC9-SpaceNav.h"



#pragma warning(disable : 4996)
void RBC9_Wait(short MilliSec)
{
	LARGE_INTEGER time;

	time.QuadPart = -10 * 1000 * MilliSec;
	KeDelayExecutionThread(KernelMode, FALSE, &time);

}

VOID RBC9_Create_Next_From(PBIND_LIST NewBind,
						   BIND_FROM BindFrom,UCHAR Num,BOOLEAN Invert,short MinVal,short MaxVal,short AxePart)
{



	NewBind->BindFrom = BindFrom;
	switch (BindFrom)
	{
	case BIND_FROM_AXE:

		NewBind->FromAxe.NumAxe = Num;
		NewBind->FromAxe.Invert = Invert;
		NewBind->FromAxe.DeadVal = 0;
		NewBind->FromAxe.MinVal = MinVal;
		NewBind->FromAxe.MaxVal = MaxVal;
		NewBind->FromAxe.AxePart = AxePart;
		break;

	case BIND_FROM_BTN:

		NewBind->FromBtn.NumBtn = Num;
		NewBind->FromBtn.Invert = Invert;
		NewBind->FromBtn.FalseVal = MinVal;
		NewBind->FromBtn.TrueVal = MaxVal;
		NewBind->FromType.Type = AxePart;
		NewBind->FromType.Delay = 500;


		if	((NewBind->FromBtn.FalseVal ==0) && (NewBind->FromBtn.TrueVal==0))
			NewBind->FromBtn.TrueVal = 1;

		break;
	}

}

VOID RBC9_Create_Next_To(PBIND_LIST NewBind, BIND_TO BindTo,short Param)
{

	NewBind->BindTo = BindTo;

	switch (BindTo)
	{
	case BIND_TO_JOYSTICK_AXE:

		NewBind->Joy.Axe = (CHAR) Param;
		if(NewBind->Joy.Axe > (INPUT_REPORT_NUM_JOY_AXE-1)) NewBind->Joy.Axe=(INPUT_REPORT_NUM_JOY_AXE-1);
		break;

	case BIND_TO_JOYSTICK_BTN:

		NewBind->Joy.Btn = (CHAR) Param;
		if(NewBind->Joy.Btn > (INPUT_REPORT_NUM_JOY_BUTTON-1)) NewBind->Joy.Btn=(INPUT_REPORT_NUM_JOY_BUTTON-1);
		break;

	case BIND_TO_JOYSTICK_POV:

		NewBind->Joy.POV = (CHAR) Param;
		if (NewBind->Joy.POV > 1) NewBind->Joy.POV = 1;
		break;

	case BIND_TO_MOUSE_X:
		NewBind->Mou.Sensi = (CHAR) Param;
		break;

	case BIND_TO_MOUSE_Y:

		NewBind->Mou.Sensi = (CHAR) Param;
		break;
	case BIND_TO_MOUSE_WHEEL:

		NewBind->Mou.Wheel_Speed = (CHAR) Param;
		break;

	case BIND_TO_MOUSE_BTN:

		NewBind->Mou.Btn = (CHAR) Param;
		if(NewBind->Mou.Btn > (INPUT_REPORT_NUM_MOU_BUTTON-1)) NewBind->Mou.Btn=(INPUT_REPORT_NUM_MOU_BUTTON-1);
		break;

	case BIND_TO_PROFIL:

		NewBind->Profil_Id = Param;
		break;

	case BIND_TO_WWW:
			NewBind->www = (CHAR) Param;
		break;

	}

}

VOID RBC9_Create_NextBind(PBIND_LIST *LastBind,
						  BIND_FROM BindFrom,UCHAR Num,BOOLEAN Invert,short MinVal,short MaxVal,short AxePart,
						  BIND_TO BindTo,short Param
								)
{
	PBIND_LIST NewBind = (PBIND_LIST)  ExAllocatePool(NonPagedPool, sizeof(BIND_LIST));

	if (NewBind == NULL)
	{
		DBG_LEAVE(("ExAllocatePool Error"));
		return;
	}

	NewBind->NextBind = *LastBind;
	*LastBind = NewBind;

	RBC9_Create_Next_From(NewBind,BindFrom,Num,Invert,MinVal,MaxVal,AxePart);

	RBC9_Create_Next_To(NewBind,BindTo,Param);

}

VOID RBC9_Create_NextBind_KEYB(PBIND_LIST *LastBind,
							   BIND_FROM BindFrom,UCHAR Num,BOOLEAN Invert,short MinVal,short MaxVal,short AxePart,
							   BIND_TO BindTo,KEY_BIND Param
							   )
{
	PBIND_LIST NewBind = (PBIND_LIST)  ExAllocatePool(NonPagedPool, sizeof(BIND_LIST));

	if (NewBind == NULL)
	{
		DBG_LEAVE(("ExAllocatePool Error"));
		return;
	}

	NewBind->NextBind = *LastBind;
	*LastBind = NewBind;

	RBC9_Create_Next_From(NewBind,BindFrom,Num,Invert,MinVal,MaxVal,AxePart);

	NewBind->BindTo = BindTo;

	NewBind->Key = Param;

}


PPROFIL RBC9_Profil_ZERO(IN PDEVICE_OBJECT pDev_obj)
{

	PPROFIL		Profil_First = (PPROFIL)  ExAllocatePool(NonPagedPool, sizeof(PROFIL));
	PBIND_LIST	Bind_Liste;	
	KEY_BIND	MyKeyTest;

	DBG_ENTER((""));

	if (Profil_First == NULL)
	{
		DBG_LEAVE(("ExAllocatePool Error"));
		return NULL;
	}

	Profil_First->Profil_Id = -1;
	Profil_First->NextProfil = NULL;

	RtlCopyMemory(&Profil_First->ProfilName[0], L"Base Profil", sizeof(L"Base Profil"));

	Profil_First->DeadVal = 50; /* % Dead */

	Profil_First->Bind_Liste = NULL;

	RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_AXE,3,FALSE,15,0,AXE_ALL,BIND_TO_JOYSTICK_POV,POV_VERT);
	RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_AXE,4,FALSE,15,0,AXE_ALL,BIND_TO_JOYSTICK_POV,POV_HORI);

	RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_AXE,0,FALSE,0,0,AXE_ALL,BIND_TO_JOYSTICK_AXE,0);
	RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_AXE,1,FALSE,0,0,AXE_ALL,BIND_TO_JOYSTICK_AXE,1);
	RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_AXE,2,FALSE,0,0,AXE_ALL,BIND_TO_JOYSTICK_AXE,2);
	RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_AXE,4,FALSE,0,0,AXE_ALL,BIND_TO_JOYSTICK_AXE,3);
	RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_AXE,3,FALSE,0,0,AXE_ALL,BIND_TO_JOYSTICK_AXE,4);
	RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_AXE,5,FALSE,0,0,AXE_ALL,BIND_TO_JOYSTICK_AXE,5);
	RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_AXE,5,TRUE,0,0,AXE_POS,BIND_TO_JOYSTICK_AXE,6);

	RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_BTN,1,FALSE,0,350,0,BIND_TO_JOYSTICK_AXE,7);
	RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_BTN,1,TRUE,0,-350,0,BIND_TO_JOYSTICK_AXE,7);

	RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_BTN,0,FALSE,0,1,0,BIND_TO_JOYSTICK_BTN,0);
	RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_BTN,0,TRUE,0,1,0,BIND_TO_JOYSTICK_BTN,1);
	RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_BTN,1,FALSE,0,1,0,BIND_TO_JOYSTICK_BTN,4);

	RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_AXE,4,FALSE,0,0,AXE_ALL,BIND_TO_MOUSE_X,100);
	RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_AXE,3,FALSE,0,0,AXE_ALL,BIND_TO_MOUSE_Y,100);
	RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_AXE,5,TRUE,10,0,AXE_ALL,BIND_TO_MOUSE_WHEEL,500);

	//RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_BTN,0,FALSE,0,0,0,BIND_TO_MOUSE_BTN,0);
	//RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_BTN,1,FALSE,0,0,0,BIND_TO_MOUSE_BTN,1);

	RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_BTN,0,FALSE,0,0,0,BIND_TO_WWW,0x02);
	RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_BTN,1,FALSE,0,0,0,BIND_TO_WWW,0x03);

	//RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_BTN,1,FALSE,0,0,0,BIND_TO_PROFIL,25);

	//RBC9_Create_NextBind(&Profil_First->Bind_Liste,BIND_FROM_BTN,1,FALSE,0,0,0,BIND_TO_TEST,0);

/*	RtlZeroMemory(&MyKeyTest, sizeof(MyKeyTest));

	MyKeyTest.Event = KEY_BTN;
	MyKeyTest.FireDelay = 0;
	MyKeyTest.Code[0]=0x04;

	RBC9_Create_NextBind_KEYB(&Profil_First->Bind_Liste,BIND_FROM_BTN,0,FALSE,0,0,BTN_LONG,BIND_TO_KEYB,MyKeyTest);
	
	MyKeyTest.Code[0]=0x05;

	RBC9_Create_NextBind_KEYB(&Profil_First->Bind_Liste,BIND_FROM_BTN,0,FALSE,0,0,BTN_SHORT,BIND_TO_KEYB,MyKeyTest);

	//MyKeyTest.Code[0]=0x05;
	//MyKeyTest.Code[1]=0x06;
	//MyKeyTest.Code[2]=0x07;
	//MyKeyTest.Code[3]=0x08;
	MyKeyTest.Code[0]=0x08;
	MyKeyTest.Code[1]=0x00;
	RBC9_Create_NextBind_KEYB(&Profil_First->Bind_Liste,BIND_FROM_BTN,1,FALSE,0,0,0,BIND_TO_WWW,MyKeyTest);

	MyKeyTest.Event = KEY_REPEAT;
	MyKeyTest.FireDelay = 500;
	MyKeyTest.Code[0]=0x2b;
	RBC9_Create_NextBind_KEYB(&Profil_First->Bind_Liste,BIND_FROM_AXE,2,FALSE,180,0,AXE_POS,BIND_TO_KEYB,MyKeyTest);
	*/
	
		DBG_LEAVE((""));

	return Profil_First;
}

VOID RBC9_Load_Profil(IN PDEVICE_OBJECT pDev_obj,IN PWSTR LayerName)
{
	PDEVICE_EXTENSION		pDevExt=GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	PPROFIL					*FirsProfil=&pDevExt->Profil_First;
	NTSTATUS				Status;

	HANDLE					LayerKey;

	PPROFIL					NewProfil;

	LONG					_Profil_Id;
	LONG					_DeadZone;

	unsigned int			BindBcl;
	unsigned int			BindNbr;
	WCHAR					BindName[256];
	UNICODE_STRING			BindKeyName;
	LONG					BindType;
	PBIND_LIST				NewBind;

		DBG_ENTER(("Open Layer %ws",LayerName));

	LayerKey = RBC9_Open_Reg(pDevExt->RegPath.Buffer,LayerName);
	if(LayerKey == NULL) 
	{
		DBG_LEAVE(("STATUS_OBJECT_NAME_NOT_FOUND"));
		return ;
	}

	Status = RBC9_Get_DWORD(LayerKey, L"Profil_Id", &_Profil_Id, 0);

	if(! NT_SUCCESS(Status)) {
		ZwClose(LayerKey);
		DBG_LEAVE(("Profil_Id Not Found %x", Status));
		return;
	}

	if ( RBC9_Profil_Exist(pDev_obj,(short)_Profil_Id))
	{
			ZwClose(LayerKey);
			DBG_LEAVE(("Profil_Id %d Already Exist %x",_Profil_Id, Status));
			return;
	}


	NewProfil = (PPROFIL)  ExAllocatePool(NonPagedPool, sizeof(PROFIL));

	NewProfil->Profil_Id	= (short)_Profil_Id;
	NewProfil->NextProfil	= *FirsProfil;
	*FirsProfil				= NewProfil;

	NewProfil->Bind_Liste = NULL;

	RBC9_Get_STRING(LayerKey, L"Profil_Name", NewProfil->ProfilName, sizeof(NewProfil->ProfilName));
	RBC9_Get_DWORD(LayerKey, L"DeadZone", &_DeadZone, 0);

	NewProfil->DeadVal = (short)_DeadZone;

	DBG_OUT(("Profil_Id %d - Profil_Name %ws  - DeadZone %d ",_Profil_Id,NewProfil->ProfilName,_DeadZone));

	if(NT_SUCCESS(RBC9_Get_Key_Info(LayerKey,NULL,&BindNbr))) 
	{

		RtlInitUnicodeString(&BindKeyName, L"Bind - ");

		for (BindBcl = 0 ;BindBcl <  BindNbr;BindBcl++)
		{
			if(NT_SUCCESS(RBC9_Get_Value_Info(LayerKey,BindBcl,BindName,256,&BindType))) 
			{
				if (BindType == REG_BINARY)
				{
					if(RtlCompareMemory(BindName, BindKeyName.Buffer,BindKeyName.Length) == BindKeyName.Length) 
					{
						//DBG_OUT(("Bind %ws OK",BindName));

						NewBind = (PBIND_LIST)  ExAllocatePool(NonPagedPool, sizeof(BIND_LIST));

						if (NewBind != NULL)
						{
							RtlZeroMemory(NewBind, sizeof(BIND_LIST));
							RBC9_Get_BINARY(LayerKey,BindName,NewBind,sizeof(BIND_LIST)-sizeof(NAV_STATUS)-sizeof(PBIND_LIST));
						//	DBG_OUT(("Read Bind %d %d %d",sizeof(BIND_LIST),NewBind->BindFrom,NewBind->BindTo));
						
							RtlZeroMemory(&NewBind->Nav, sizeof(NewBind->Nav));

							NewBind->NextBind = NewProfil->Bind_Liste;
						
							NewProfil->Bind_Liste = NewBind;

						}
					}
				}
			}
		}
	}


	ZwClose(LayerKey);

	DBG_LEAVE((""));
}

VOID RBC9_Get_Profils(IN PDEVICE_OBJECT pDev_obj)
{
	PDEVICE_EXTENSION		pDevExt=GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	NTSTATUS				Status;

	HANDLE					RegKey;

	unsigned int			LayerBcl;
	unsigned int			LayerNbr;
	WCHAR					LayerName[256];
	UNICODE_STRING			LayerKeyName;

	LONG					_Default_Profil;

	DBG_ENTER((""));


	/* open key */
	RegKey = RBC9_Open_Reg(pDevExt->RegPath.Buffer,NULL);
	if(RegKey == NULL) {
		DBG_LEAVE(("STATUS_OBJECT_NAME_NOT_FOUND"));
		return ;
	}

	/* Nombre de profil ? */
	Status = RBC9_Get_Key_Info(RegKey,&LayerNbr,NULL);
	if(! NT_SUCCESS(Status)) {
		DBG_LEAVE(("Error Get Info Key %x", Status));
		return;
	}


	RBC9_Get_DWORD(RegKey, L"Default_Profil", &_Default_Profil, 0);

	pDevExt->Profil_Id = (short)_Default_Profil;

	RtlInitUnicodeString(&LayerKeyName, L"Layout - ");

	for (LayerBcl = 0;LayerBcl < LayerNbr;LayerBcl++)	
	{
		Status = RBC9_Get_SubKey_Name(RegKey,LayerBcl,LayerName,256);
		if(NT_SUCCESS(Status)) 
		{
			if(RtlCompareMemory(LayerName, LayerKeyName.Buffer,LayerKeyName.Length) == LayerKeyName.Length) 
			{
				RBC9_Load_Profil(pDev_obj,LayerName);
			}
		}
	}


	ZwClose(RegKey);

	DBG_LEAVE(("Fin OK %x",Status));
}

VOID RBC9_InitState(IN PDEVICE_OBJECT pDev_obj)
{
	PDEVICE_EXTENSION	pDevExt;
	unsigned int		index;
	short				ActifProfil;
	DBG_ENTER(("Build - %d",DRIVER_VERSION_BUILD));

	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	if (pDevExt->Profil_Actif != NULL)
	{
		ActifProfil = pDevExt->Profil_Actif->Profil_Id;
	}
	else
	{
		ActifProfil = -1;
	}

	RBC9_Delete_Profil(pDev_obj);
	pDevExt->Profil_First = RBC9_Profil_ZERO(pDev_obj);
	pDevExt->Profil_Actif = NULL;

	RBC9_Get_Profils(pDev_obj);

	RBC9_Led_Queue_Delete(pDev_obj);

	pDevExt->Special_Action.Running = FALSE;
	pDevExt->Special_Action.Time_Action = 0;
	pDevExt->Special_Action.Start_Detect = 0;
	pDevExt->Special_Action.MinTime = 1500;

	//DBG_OUT(("Init Change x-%d",DRIVER_VERSION_BUILD));
	//	pDevExt->hid_input_changed = INPUT_TYPE_JOYSTICK | INPUT_TYPE_NAV_ALL | INPUT_TYPE_MOUSE | INPUT_TYPE_WWW | INPUT_TYPE_KEYBOARD;
	pDevExt->hid_input_changed = INPUT_TYPE_ALL;


	RtlZeroMemory(&pDevExt->hwInData, sizeof(pDevExt->hwInData));

	RtlZeroMemory(&pDevExt->input_state, sizeof(pDevExt->input_state));
	pDevExt->input_state.joy.report_id = REPORT_ID_JOY;
	pDevExt->input_state.kbd.report_id = REPORT_ID_KEY;
	pDevExt->input_state.www.report_id = REPORT_ID_WWWKEY;
	pDevExt->input_state.mou.report_id = REPORT_ID_MOU;
	pDevExt->input_state.Info.report_id = REPORT_ID_CMD;
	pDevExt->input_state.SpaceNav.Trame[0].report_id = REPORT_ID_NAV_ID1;
	pDevExt->input_state.SpaceNav.Trame[1].report_id = REPORT_ID_NAV_ID2;
	pDevExt->input_state.SpaceNav.Trame[2].report_id = REPORT_ID_NAV_ID3;

	for(index=0; index<INPUT_REPORT_NUM_JOY_AXE; pDevExt->input_state.joy.axis[index++]=JOY_OFFSET);

	RtlZeroMemory(&pDevExt->KeyB, sizeof(pDevExt->KeyB));
	RtlZeroMemory(&pDevExt->Mouse, sizeof(pDevExt->Mouse));

	if (ActifProfil != -1)
	{
		pDevExt->Profil_Actif = RBC9_Select_Profil(pDev_obj,ActifProfil);
	}
	else
	{
		pDevExt->Profil_Actif = RBC9_Select_Profil(pDev_obj,pDevExt->Profil_Id);
	}

	RBC9_SEQ_Init_HID(pDev_obj);

	DBG_LEAVE((""));
}	

VOID RBC9_Delete_Bind(IN PPROFIL ClearProfil)
{
	PBIND_LIST	FirstBind;
	PBIND_LIST	NextBind;
	//	int			BindNum=1;

	DBG_ENTER((""));


	FirstBind = ClearProfil->Bind_Liste;

	while(FirstBind !=NULL)
	{
		NextBind = FirstBind->NextBind;

		//		DBG_OUT(("Delete Bind %d",BindNum++));
		ExFreePool(FirstBind);

		FirstBind = NextBind;
	}

	DBG_LEAVE((""));	
}

VOID RBC9_Delete_Profil(IN PDEVICE_OBJECT pDev_obj)
{
	PDEVICE_EXTENSION	pDevExt= GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	PPROFIL				FirstProfil;
	PPROFIL				NextProfil;

	DBG_ENTER(("%p", pDev_obj));

	FirstProfil=pDevExt->Profil_First;
	pDevExt->Profil_First = NULL;
	pDevExt->Profil_Actif = NULL;

	while(FirstProfil !=NULL)
	{
		NextProfil = FirstProfil->NextProfil;

		DBG_OUT(("Delete Profil : %ws",FirstProfil->ProfilName));
		RBC9_Delete_Bind(FirstProfil);

		ExFreePool(FirstProfil);

		FirstProfil = NextProfil;

	}

	DBG_LEAVE((""));
}

BOOLEAN RBC9_Profil_Exist(IN PDEVICE_OBJECT pDev_obj,short Profil_Id)
{
	PDEVICE_EXTENSION		pDevExt= GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	PPROFIL					SelectProfil=pDevExt->Profil_First;

	DBG_ENTER(("%p Check Profil %d", pDev_obj,Profil_Id));
	while(SelectProfil != NULL)
	{
		if(SelectProfil->Profil_Id == Profil_Id)
		{
			DBG_LEAVE(("Check Found Profil %d ",Profil_Id));

			return TRUE;
		}
		SelectProfil = SelectProfil->NextProfil;
	}

	DBG_LEAVE(("OK Not Found"));
	return FALSE;
}

PPROFIL RBC9_Select_Profil(IN PDEVICE_OBJECT pDev_obj,short Profil_Id)
{
	PDEVICE_EXTENSION		pDevExt= GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	PPROFIL					SelectProfil=pDevExt->Profil_First;

	DBG_ENTER(("%p Search Profil %d", pDev_obj,Profil_Id));
	while(SelectProfil != NULL)
	{
		if(SelectProfil->Profil_Id == Profil_Id)
		{
			DBG_LEAVE(("Found Profil %d ",Profil_Id));
			RBC9_Clear_KeyB_Buffer(pDev_obj,TRUE);
			RBC9_SEQ_Change_Profil(pDev_obj);
			return SelectProfil;
		}
		SelectProfil = SelectProfil->NextProfil;
	}

	if ((Profil_Id != pDevExt->Profil_Id) & (Profil_Id != -1))
	{
		DBG_OUT(("Profil %d Not Found look for default %d",Profil_Id,pDevExt->Profil_Id));
		return RBC9_Select_Profil(pDev_obj,pDevExt->Profil_Id);
	}

	if (Profil_Id != -1)
	{
		DBG_OUT(("Profil %d Not Found look for -1",Profil_Id));
		return RBC9_Select_Profil(pDev_obj,-1);
	}

	DBG_LEAVE(("Not Found"));
	return NULL;
}

VOID RBC9_Select_Next_Profil(IN PDEVICE_OBJECT pDev_obj)
{

	PDEVICE_EXTENSION	pDevExt= GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	RBC9_SEQ_Change_Profil(pDev_obj);

	pDevExt->Profil_Actif = pDevExt->Profil_Actif->NextProfil;
	if(pDevExt->Profil_Actif == NULL)
	{
		pDevExt->Profil_Actif = pDevExt->Profil_First;
	}

	DBG_OUT(("Switch to %d",pDevExt->Profil_Actif->Profil_Id));
}



short RBC9_NavState(PBIND_LIST BindToDo,BOOLEAN OnVal,short TrueVal,short FalseVal)
{
	ULONGLONG			cur_time	= KeQueryInterruptTime();

	if (OnVal != BindToDo->Nav.Last_On)
	{
		BindToDo->Nav.Last_On = OnVal;

		if (OnVal)
		{
			BindToDo->Nav.Last_Press = cur_time;
			BindToDo->Nav.Last_Val = TrueVal;
		}
		else
		{
			BindToDo->Nav.Last_Release = cur_time;
		}

	}

	switch (BindToDo->FromType.Type)
	{
	case PRESS_STD:
		return OnVal ? TrueVal : FalseVal;
		break;


	case PRESS_SHORT:
		
		if (!OnVal)
		{
			if (cur_time < (BindToDo->Nav.Last_Release + (1 * 10 * 1000)))
			{
				if ( (BindToDo->Nav.Last_Release - BindToDo->Nav.Last_Press) < (BindToDo->FromType.Delay * 10 * 1000))
				{
					return BindToDo->Nav.Last_Val;
				}
			}
		}
		
		break;

	case PRESS_LONG:

		if (OnVal)
		{
			if (cur_time > (BindToDo->Nav.Last_Press + (BindToDo->FromType.Delay * 10 * 1000)))
			{
				return TrueVal;
			}

		}
		break;
	}


	return FalseVal;

}
short RBC9_Get_AxeVal(IN PDEVICE_OBJECT pDev_obj,PBIND_LIST BindToDo)
{
	PDEVICE_EXTENSION	pDevExt= GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	short				NewVal;
	short				New_Max_Value;
	short				CurDeadVal;
	short Signe;
	
	NewVal = pDevExt->input_state.SpaceNav.Trame[BindToDo->FromAxe.NumAxe / 3].Axe[BindToDo->FromAxe.NumAxe % 3];

	if (BindToDo->FromAxe.NumAxe == 4) NewVal *=-1;
	
	Signe = NewVal >= 0 ? 1 : -1;
	
	NewVal = (short) abs(NewVal);

	CurDeadVal = pDevExt->Profil_Actif->DeadVal + BindToDo->FromAxe.DeadVal;
	
	if (CurDeadVal >= NAV_MAX_VALUE)
	{
		CurDeadVal = NAV_MAX_VALUE-1;
	}
	New_Max_Value = NAV_MAX_VALUE - CurDeadVal;

	if(NewVal >= CurDeadVal)
	{
		NewVal=(short) NewVal - CurDeadVal;
	}
	else
	{
		NewVal = 0;
	}

	NewVal = (NewVal * NAV_MAX_VALUE) / New_Max_Value;

	if(NewVal > NAV_MAX_VALUE)
	{
		NewVal=(short)(NAV_MAX_VALUE);	
	}

	if(NewVal < BindToDo->FromAxe.MinVal )
	{
		NewVal =0;
	}

	if((NewVal > BindToDo->FromAxe.MaxVal ) && (BindToDo->FromAxe.MaxVal !=0))
	{
		NewVal =0;
	}

	NewVal= NewVal * Signe;

	if(BindToDo->FromAxe.Invert)
	{
		NewVal= NewVal * (-1);
	}

	switch (BindToDo->FromAxe.AxePart)
	{
	case AXE_POS:
		if(NewVal <0)
		{
			NewVal = 0;
		}
		break;
	case AXE_NEG:
		if(NewVal >0)
		{
			NewVal = 0;
		}
		break;
	}

//DBG_OUT(("%d",NewVal));

	return RBC9_NavState(BindToDo,(NewVal != 0)  ,NewVal,0);

}
short RBC9_Get_BtnVal(IN PDEVICE_OBJECT pDev_obj,PBIND_LIST BindToDo)
{
	PDEVICE_EXTENSION	pDevExt		= GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	CHAR				BitMask;
	BOOLEAN				NewVal = FALSE;

	BitMask = 1 << (BindToDo->FromBtn.NumBtn % 8);

	NewVal = ((pDevExt->input_state.SpaceNav.Trame[2].Btn[BindToDo->FromBtn.NumBtn / 8] & BitMask) == BitMask);

	if(BindToDo->FromBtn.Invert)
	{
		NewVal = ! NewVal;
	}

	return RBC9_NavState(BindToDo,NewVal,BindToDo->FromBtn.TrueVal,BindToDo->FromBtn.FalseVal);
	
}

short RBC9_Get_Val(IN PDEVICE_OBJECT pDev_obj,PBIND_LIST BindToDo)
{

	switch (BindToDo->BindFrom)
	{
	case BIND_FROM_AXE:
		return RBC9_Get_AxeVal(pDev_obj,BindToDo);
		break;

	case BIND_FROM_BTN:
		return RBC9_Get_BtnVal(pDev_obj,BindToDo);
		break;
	}
	return 0;
}

__int16 RBC9_Get_POV(IN BIND_POV Bind_Pov,short ValIn)
{

	int			JOY_POVBits[4] = {0x01,0x02,0x04,0x08}; // UP Right Down Left
	__int16		Tmp_POVBits=0;
	short		Vert;
	short		Hori;


	Vert = 0;
	Hori = 0;

	switch (Bind_Pov)
	{
	case POV_VERT:
		Vert=ValIn;
		break;

	case POV_HORI:
		Hori=ValIn;
		break;
	}


	if (Vert <0)
	{
		Tmp_POVBits |= JOY_POVBits[0];
	}

	if (Vert >0)
	{
		Tmp_POVBits |= JOY_POVBits[2];
	}

	if (Hori <0)
	{
		Tmp_POVBits |= JOY_POVBits[3];
	}

	if (Hori >0)
	{
		Tmp_POVBits |= JOY_POVBits[1];
	}


	return Tmp_POVBits;
}



CHAR RBC9_Get_Mouse(short ValIn,UCHAR Sensi)
{

	long MouseVal;
	long ValCarre;

	short Signe;

	Signe = ValIn >= 0 ? 1 : -1;

	ValCarre = ValIn  *  ValIn;

	MouseVal = abs ((ValCarre * MOU_MAX_VALUE * Sensi) / (NAV_MAX_CARRE *100)) ;

	if(MouseVal > MOU_MAX_VALUE)
	{
		MouseVal = MOU_MAX_VALUE;
	}

	MouseVal = Signe * MouseVal;

	return (CHAR) MouseVal;
}



VOID RBC9_Get_Wheel(PDEVICE_EXTENSION pDevExt,PBIND_LIST BindToDo,short ValIn)
{

	short PasWheel;
	short Signe;

	Signe = ValIn >= 0 ? 1 : -1;

	pDevExt->Mouse.wheel_wait = (LONG) (((abs(ValIn) - NAV_VALUE_QUICK) * (MOU_DELAY_QUICK - (BindToDo->Mou.Wheel_Speed * 10 )))
		/(NAV_VALUE_QUICK-NAV_VALUE_LENT))
		+ MOU_DELAY_QUICK;

	PasWheel = 1;
	if(abs(ValIn) >= NAV_MAX_VALUE/3)   pDevExt->Mouse.wheel_wait /= 2;
	if(abs(ValIn) >= NAV_MAX_VALUE-60)	PasWheel = 10;
	if(abs(ValIn) >= NAV_MAX_VALUE-30)	PasWheel = 25;

	pDevExt->Mouse.wheel_val =   PasWheel * Signe;

	//	DBG_INFO(("Mouse Wheel %d %d %d ",ValIn,pDevExt->Mouse.wheel_val,pDevExt->Mouse.wheel_wait));
	//DBG_OUT(("Speed Wheel %d ",BindToDo->Mou.Wheel_Speed));

}


VOID RBC9_Get_KeyB(PDEVICE_EXTENSION pDevExt,PBIND_LIST BindToDo)
{
	short BclKey;
	UCHAR KeyCode;

	for(BclKey = 0;BclKey < sizeof(BindToDo->Key.Code);BclKey++)
	{
		if((BindToDo->Key.Code[BclKey]!=0) && (BindToDo->Key.Code[BclKey]< INPUT_REPORT_NUM_KBD_CODE))
		{
			//DBG_OUT(("Key %x",BindToDo->Key.Code[BclKey]));


			//	 numbyte = (int) KeyCode;

			//DBG_OUT(("Key %d %d",numbyte,KeyCode / 8));

			KeyCode = BindToDo->Key.Code[BclKey];

			pDevExt->KeyB.Key[KeyCode].Event |= BindToDo->Key.Event;

			if(BindToDo->Key.Event & KEY_RELEASE)
			{
				pDevExt->KeyB.Key[KeyCode].Event &= ~KEY_KEEP;
			}

			if(BindToDo->Key.Event & KEY_REPEAT)
			{
				if((pDevExt->KeyB.Key[KeyCode].Fire_Delay == 0)|| (BindToDo->Key.FireDelay <pDevExt->KeyB.Key[KeyCode].Fire_Delay))
				{
					pDevExt->KeyB.Key[KeyCode].Fire_Delay = BindToDo->Key.FireDelay;
				}
			}

		}
	}
}

VOID RBC9_KeyB_Buffer(IN PDEVICE_OBJECT pDev_obj)
{
	PDEVICE_EXTENSION			pDevExt		= GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	ULONGLONG					cur_time	= KeQueryInterruptTime();
	UCHAR						BclBuf;
	short						PosKey		= 0;
	BOOLEAN						TurnOn;


	pDevExt->input_state.kbd.Modifier =0;
	RtlZeroMemory(&pDevExt->input_state.kbd.keys, sizeof(pDevExt->input_state.kbd.keys));

	for (BclBuf = 0;BclBuf < INPUT_REPORT_NUM_KBD_CODE;BclBuf++)
	{

		if((pDevExt->KeyB.Key[BclBuf].Event  & KEY_BTN) || (pDevExt->KeyB.Key[BclBuf].Event  & KEY_KEEP))
		{
			TurnOn = FALSE;

			if(pDevExt->KeyB.Key[BclBuf].Event  & KEY_REPEAT)
			{
				
				if(cur_time >= pDevExt->KeyB.Key[BclBuf].Last_Fire + (pDevExt->KeyB.Key[BclBuf].Fire_Delay * 10 * 1000)) 
				{
					TurnOn = TRUE;
					//DBG_OUT(("Key Repeat : %x ? %d ",BclBuf,TurnOn));
				}
				
			}
			else
			{
				TurnOn = TRUE;
				//DBG_OUT(("Key On : %x ",BclBuf));
			}


			if (TurnOn)
			{
				if (BclBuf < KEY_BASE_MODIFIER)
				{
				//	DBG_OUT(("Key Std"));

					if (PosKey < KEY_MAX_KEY)
					{
						pDevExt->KeyB.Key[BclBuf].Last_Fire = cur_time;
						pDevExt->input_state.kbd.keys[PosKey++] = BclBuf;

						//DBG_OUT(("Key Std  ---> Add"));
					}
				}
				else
				{
					// modifier
					pDevExt->KeyB.Key[BclBuf].Last_Fire = cur_time;
					pDevExt->input_state.kbd.Modifier |= 1 << (BclBuf -  KEY_BASE_MODIFIER);

					//DBG_OUT(("Key Modifier"));
				}

			}
		}
		else
		{
			pDevExt->KeyB.Key[BclBuf].Last_Fire = 0;
		}

	}

}


VOID RBC9_Get_WWW(PDEVICE_EXTENSION pDevExt,PBIND_LIST BindToDo)
{

	UCHAR KeyCode;


	if((BindToDo->www!=0) && (BindToDo->www<= INPUT_REPORT_NUM_WWW_CODE))
	{

		KeyCode = BindToDo->www-1;

		//DBG_OUT(("WWW Key Press %d %d %d",KeyCode,KeyCode / 8,KeyCode % 8));

		pDevExt->input_state.www.keys[KeyCode / 8]  |= 1 << (KeyCode % 8);

	}

}






VOID RBC9_Set_Info(IN PDEVICE_OBJECT pDev_obj)
{
	PDEVICE_EXTENSION	pDevExt		= GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	
	pDevExt->input_state.Info.Ctrl = 1;

	if (pDevExt->Profil_Actif != NULL)
	{
		pDevExt->input_state.Info.Profil_Id = pDevExt->Profil_Actif->Profil_Id;
	}
	else
	{
	    pDevExt->input_state.Info.Profil_Id = -1;
	}

}

VOID RBC9_Set_Navigator(IN PDEVICE_OBJECT pDev_obj)
{
	PDEVICE_EXTENSION	pDevExt		= GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	int					BclAxe;
	//	DBG_ENTER(("%p", pDev_obj));

	

	if ((pDevExt->hwInData.ReportId == REPORT_ID_NAV_ID1) || (pDevExt->hwInData.ReportId == REPORT_ID_NAV_ID2)|| (pDevExt->hwInData.ReportId == REPORT_ID_NAV_ID3))
	{
		pDevExt->input_state.SpaceNav.Trame[pDevExt->hwInData.ReportId-1].Axe[0] =  pDevExt->hwInData.Axe[0];
		pDevExt->input_state.SpaceNav.Trame[pDevExt->hwInData.ReportId-1].Axe[1] =  pDevExt->hwInData.Axe[1];
		pDevExt->input_state.SpaceNav.Trame[pDevExt->hwInData.ReportId-1].Axe[2] =  pDevExt->hwInData.Axe[2];

		if(pDevExt->hwInData.ReportId != REPORT_ID_NAV_ID3)
		{
			for(BclAxe = 0;BclAxe < 3; BclAxe++)
			{
				if(abs(pDevExt->input_state.SpaceNav.Trame[pDevExt->hwInData.ReportId-1].Axe[BclAxe]) > NAV_MAX_VALUE)
				{
					pDevExt->input_state.SpaceNav.Trame[pDevExt->hwInData.ReportId-1].Axe[BclAxe]=(short)((pDevExt->input_state.SpaceNav.Trame[pDevExt->hwInData.ReportId-1].Axe[BclAxe] >0) ? NAV_MAX_VALUE : -NAV_MAX_VALUE);	
				}
			}
		}
	}


	//	DBG_LEAVE((""));
}



VOID RBC9_Clear_KeyB_Buffer(IN PDEVICE_OBJECT pDev_obj,BOOLEAN ClearKeep)
{

	PDEVICE_EXTENSION			pDevExt			=	GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	unsigned int				index;

	for(index=0; index<INPUT_REPORT_NUM_KBD_CODE; index++)
	{

		if (!(pDevExt->KeyB.Key[index].Event & KEY_KEEP)|| ClearKeep)
		{
			pDevExt->KeyB.Key[index].Event = 0;
			pDevExt->KeyB.Key[index].Fire_Delay=0;
		}
	}

}


VOID RBC9_Clear_State(IN PDEVICE_OBJECT pDev_obj)
{
	PDEVICE_EXTENSION			pDevExt			=	GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	unsigned int				index;

	for(index=0; index<INPUT_REPORT_NUM_JOY_AXE; pDevExt->input_state.joy.axis[index++]=JOY_OFFSET);
	pDevExt->input_state.joy.button = 0;
	
	pDevExt->input_state.mou.x = 0;
	pDevExt->input_state.mou.y = 0;
	pDevExt->input_state.mou.button = 0;
	pDevExt->input_state.mou.wheel = 0;
	pDevExt->Mouse.wheel_val = 0;
	

	RtlZeroMemory(&pDevExt->input_state.www.keys, sizeof(pDevExt->input_state.www.keys));

	RBC9_Clear_KeyB_Buffer(pDev_obj,FALSE);
	
}

VOID RBC9_Do_Bind(IN PDEVICE_OBJECT pDev_obj)
{

	PDEVICE_EXTENSION			pDevExt			=	GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	PPROFIL						Profil_Actif	=	pDevExt->Profil_Actif;
	PBIND_LIST					BindToDo		=	Profil_Actif->Bind_Liste;
	short						ValIn;
	short						ValTo;
	__int16						POVBits;
	unsigned int				index;
	short						SwitchProfil;

	//	DBG_ENTER(("%p", pDev_obj));


	RBC9_Clear_State(pDev_obj);

	if (pDevExt->Profil_Actif == NULL) return;

	//DBG_OUT(("buf size %d",sizeof(pDevExt->input_state.kbd.keys)));

	POVBits=0;

	SwitchProfil = pDevExt->Profil_Actif->Profil_Id;

	while(BindToDo != NULL)
	{

		ValIn = RBC9_Get_Val(pDev_obj,BindToDo);

		if(ValIn !=0)
		{


			//DBG_OUT(("Do Bind From %d - ValIn %d",BindToDo->BindFrom,ValIn));

			switch (BindToDo->BindTo)
			{
			case BIND_TO_JOYSTICK_AXE:

				ValTo = ValIn + JOY_OFFSET;
				//DBG_OUT(("Do Bind From %d - ValTo %d Axe %d",BindToDo->BindFrom,ValTo,BindToDo->Joy.Axe));
				if(abs(ValIn) > abs(pDevExt->input_state.joy.axis[BindToDo->Joy.Axe]-JOY_OFFSET))
				{
					pDevExt->input_state.joy.axis[BindToDo->Joy.Axe] = ValTo;
				}
				break;

			case BIND_TO_JOYSTICK_BTN:

				pDevExt->input_state.joy.button |= (1 << (BindToDo->Joy.Btn));
				//DBG_OUT(("Joy btn : %d",pDevExt->input_state.joy.button))
				break;

			case BIND_TO_JOYSTICK_POV:

				POVBits |= RBC9_Get_POV(BindToDo->Joy.POV,ValIn);
				break;

			case BIND_TO_MOUSE_X:

				ValTo = RBC9_Get_Mouse(ValIn,BindToDo->Mou.Sensi);
				if(abs(ValTo) > abs(pDevExt->input_state.mou.x))
				{
					pDevExt->input_state.mou.x = (char) ValTo;
				}
				//DBG_OUT(("Mouse X %d %d",pDevExt->input_state.mou.x,ValIn));
				break;

			case BIND_TO_MOUSE_Y:

				ValTo = RBC9_Get_Mouse(ValIn,BindToDo->Mou.Sensi);
				if(abs(ValTo) > abs(pDevExt->input_state.mou.y))
				{
					pDevExt->input_state.mou.y = (char) ValTo;
				}
				//DBG_OUT(("Mouse Y %d",pDevExt->input_state.mou.y));
				break;

			case BIND_TO_MOUSE_WHEEL:

				RBC9_Get_Wheel(pDevExt,BindToDo,ValIn);
				break;

			case BIND_TO_MOUSE_BTN:

				pDevExt->input_state.mou.button |=  (1 << (BindToDo->Mou.Btn));
				break;


			case BIND_TO_KEYB:

				RBC9_Get_KeyB(pDevExt,BindToDo);

				break;


			case BIND_TO_PROFIL:

				SwitchProfil = BindToDo->Profil_Id;
				break;

			case BIND_TO_WWW:

				RBC9_Get_WWW(pDevExt,BindToDo);

				break;

			}

		}
		BindToDo = BindToDo->NextBind;
	}

	pDevExt->input_state.joy.Pov = JOY_POVVal[POVBits];

	if (SwitchProfil != pDevExt->Profil_Actif->Profil_Id)
	{
		pDevExt->Profil_Actif = RBC9_Select_Profil(pDev_obj,SwitchProfil);
	}

	//	DBG_LEAVE((""));
}




BOOLEAN RBC9_Special_Action(IN PDEVICE_OBJECT pDev_obj)
{
	PDEVICE_EXTENSION			pDevExt=GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	ULONGLONG					cur_time;

	cur_time = KeQueryInterruptTime();

	if (cur_time > (pDevExt->Special_Action.Time_Action + (pDevExt->Special_Action.MinTime * 10 * 1000)))
	{

		if (!pDevExt->Special_Action.Running)
		{
	
			if ((pDevExt->input_state.SpaceNav.Trame[0].Axe[2] < -300) && (pDevExt->input_state.SpaceNav.Trame[1].Axe[2] < -300))
			{

				if (pDevExt->Special_Action.Start_Detect == 0)
				{
					pDevExt->Special_Action.Start_Detect = cur_time;
				}

				if (cur_time > (pDevExt->Special_Action.Start_Detect + (pDevExt->Special_Action.MinTime * 10 * 1000)))
				{
					pDevExt->Special_Action.Time_Action = cur_time;
					pDevExt->Special_Action.Start_Detect = 0;
					pDevExt->Special_Action.Running = TRUE;
					RBC9_SEQ_Special_Action(pDev_obj);

					RBC9_Clear_State(pDev_obj);
					RtlZeroMemory(&pDevExt->KeyB, sizeof(pDevExt->KeyB));

					return TRUE;
				}
			}	
			else
			{
				pDevExt->Special_Action.Start_Detect = 0;	
			}
		}
		else
		{

			if (pDevExt->input_state.SpaceNav.Trame[0].Axe[2] > 300)
			{
				pDevExt->Special_Action.Running = FALSE;
				RBC9_SEQ_Special_Action_Fin(pDev_obj);
				pDevExt->Special_Action.Time_Action = cur_time;
			}
			else
			{
				if (pDevExt->Led == NULL)
				{
					DBG_OUT(("Relance My Led"));
					RBC9_SEQ_Special_Action(pDev_obj);
				}	
				if (pDevExt->input_state.SpaceNav.Trame[2].Btn[0] == 0x02)
				{
					DBG_OUT(("RBC9_Select_Next_Profil"));
					RBC9_Select_Next_Profil(pDev_obj);
					pDevExt->Special_Action.Time_Action = cur_time;
				}
				if (pDevExt->input_state.SpaceNav.Trame[2].Btn[0] == 0x01)
				{
					DBG_OUT(("RBC9_Select_Default"));
					pDevExt->Profil_Actif = RBC9_Select_Profil(pDev_obj,pDevExt->Profil_Id);
					pDevExt->Special_Action.Time_Action = cur_time;
				}
			}
			return TRUE;
		}

		return FALSE;
	}

	return TRUE;
}

VOID RBC9_process_raw_input(IN PDEVICE_OBJECT pDev_obj)
{
	PDEVICE_EXTENSION			pDevExt;


	//	DBG_ENTER(("%p", pDev_obj));

	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	RBC9_Set_Navigator(pDev_obj);

	if ( !RBC9_Special_Action(pDev_obj) && !pDevExt->ModeConfig)
	{

		//DBG_OUT(("SpaceNav changed"));

			if(pDevExt->Profil_Actif != NULL)
			{
				RBC9_Do_Bind(pDev_obj);
			}
	

		RBC9_KeyB_Buffer(pDev_obj);

	};

	RBC9_Set_Info(pDev_obj);

	//	DBG_LEAVE(("void"));
}


#include "RBC9-SpaceNav.h"
#include "stdio.h"


#pragma warning(disable : 4996)

HANDLE RBC9_Open_Reg(IN PWSTR basekey,IN PWSTR subkey)
{
	WCHAR				buf[256];
	UNICODE_STRING		path;
	OBJECT_ATTRIBUTES	obj_attr;
	HANDLE				key;
	NTSTATUS			Status;

	//	DBG_ENTER(("\"%ws\"", subkey));

	RtlZeroMemory(buf, sizeof(buf));
	path.Length = 0;
	path.MaximumLength = sizeof(buf);
	path.Buffer = buf;

	RtlAppendUnicodeToString(&path, basekey);
	RtlAppendUnicodeToString(&path, L"\\Layout\\");
	RtlAppendUnicodeToString(&path, subkey);

	DBG_OUT(("newpath bis %ws", path.Buffer));

	InitializeObjectAttributes(&obj_attr, &path,
		OBJ_CASE_INSENSITIVE, NULL, NULL);

	Status = ZwOpenKey(&key, KEY_ALL_ACCESS, &obj_attr);
	if(! NT_SUCCESS(Status)) {
		DBG_LEAVE(("NULL: ZwOpenKey failed: %x", Status));
		return NULL;
	}

	//	DBG_LEAVE(("%p", key));
	return key;
}

NTSTATUS RBC9_Get_Key_Info(HANDLE key,unsigned int *NbrSubKey,unsigned int *NbrValue)
{
	NTSTATUS				Status;
	PKEY_FULL_INFORMATION	MyKeyInfo;
	ULONG					size;

	//DBG_ENTER((""));

	Status = ZwQueryKey (key,KeyFullInformation,NULL,0,&size);
	if(! NT_SUCCESS(Status) && Status != STATUS_BUFFER_TOO_SMALL) 
	{
		DBG_LEAVE(("%x", Status));
		return Status;
	}

	MyKeyInfo = (PKEY_FULL_INFORMATION)ExAllocatePool(NonPagedPool, size);
	if(MyKeyInfo == NULL) {

		DBG_LEAVE(("STATUS_INSUFFICIENT_RESOURCES"));
		return STATUS_INSUFFICIENT_RESOURCES;
	}

	Status = ZwQueryKey (key,KeyFullInformation,MyKeyInfo,size,&size);
	if(! NT_SUCCESS(Status)) 
	{
		ExFreePool(MyKeyInfo);
		DBG_LEAVE(("%x", Status));
		return Status;
	}

	if (NbrSubKey != NULL)
		*NbrSubKey = MyKeyInfo->SubKeys;
	if (NbrValue != NULL)
		*NbrValue = MyKeyInfo->Values;

	//DBG_LEAVE(("MyKeyList %d %d",MyKeyInfo->SubKeys,MyKeyInfo->MaxNameLen));

	return STATUS_SUCCESS;
}


NTSTATUS RBC9_Get_SubKey_Name(HANDLE key,unsigned int Num_SubKey,WCHAR *buf,ULONG bufsize)
{

	NTSTATUS				Status;
	ULONG					size;
	PKEY_BASIC_INFORMATION	MySubKeyInfo;

	//	DBG_ENTER((""));

	Status = ZwEnumerateKey  (key,Num_SubKey,KeyBasicInformation,NULL,0,&size);
	if(! NT_SUCCESS(Status) && Status != STATUS_BUFFER_TOO_SMALL) 
	{
		DBG_LEAVE(("STATUS_UNSUCCESSFUL %x", Status));
		return Status;
	}

	MySubKeyInfo = (PKEY_BASIC_INFORMATION)ExAllocatePool(NonPagedPool, size);
	if(MySubKeyInfo == NULL) {
		DBG_LEAVE(("STATUS_INSUFFICIENT_RESOURCES"));
		return STATUS_INSUFFICIENT_RESOURCES;
	}

	Status = ZwEnumerateKey  (key,Num_SubKey,KeyBasicInformation,MySubKeyInfo,size,&size);
	if(! NT_SUCCESS(Status)) 
	{
		ExFreePool(MySubKeyInfo);
		DBG_LEAVE(("STATUS_UNSUCCESSFUL %x", Status));
		return Status;
	}
	if (bufsize < MySubKeyInfo->NameLength)
	{
		ExFreePool(MySubKeyInfo);
		DBG_LEAVE(("STATUS_INSUFFICIENT_RESOURCES"));
		return STATUS_INSUFFICIENT_RESOURCES;
	}

	RtlZeroMemory(buf, bufsize);
	RtlCopyMemory(buf,MySubKeyInfo->Name,MySubKeyInfo->NameLength);

	//DBG_LEAVE(("SubKey %d %ws",Num_SubKey,buf));

	return STATUS_SUCCESS;
}

NTSTATUS RBC9_Get_Value_Info(HANDLE key,unsigned int Num_Value,WCHAR *buf,ULONG bufsize,ULONG * Type)
{

	NTSTATUS				Status;
	ULONG					size;
	PKEY_VALUE_BASIC_INFORMATION	MyValueInfo;

	//	DBG_ENTER((""));

	Status = ZwEnumerateValueKey  (key,Num_Value,KeyValueBasicInformation,NULL,0,&size);
	if(! NT_SUCCESS(Status) && Status != STATUS_BUFFER_TOO_SMALL) 
	{
		DBG_LEAVE(("STATUS_UNSUCCESSFUL %x", Status));
		return Status;
	}

	MyValueInfo = (PKEY_VALUE_BASIC_INFORMATION)ExAllocatePool(NonPagedPool, size);
	if(MyValueInfo == NULL) {
		DBG_LEAVE(("STATUS_INSUFFICIENT_RESOURCES"));
		return STATUS_INSUFFICIENT_RESOURCES;
	}

	Status = ZwEnumerateValueKey  (key,Num_Value,KeyValueBasicInformation,MyValueInfo,size,&size);
	if(! NT_SUCCESS(Status)) 
	{
		ExFreePool(MyValueInfo);
		DBG_LEAVE(("STATUS_UNSUCCESSFUL %x", Status));
		return Status;
	}
	if (bufsize < MyValueInfo->NameLength)
	{
		ExFreePool(MyValueInfo);
		DBG_LEAVE(("STATUS_INSUFFICIENT_RESOURCES"));
		return STATUS_INSUFFICIENT_RESOURCES;
	}

	RtlZeroMemory(buf, bufsize);
	RtlCopyMemory(buf,MyValueInfo->Name,MyValueInfo->NameLength);

	if (Type != NULL)
	{
		*Type = MyValueInfo->Type;
	}

	//DBG_LEAVE(("MyValueInfo %d %ws",Num_Value,buf));

	return STATUS_SUCCESS;
}

NTSTATUS RBC9_Set_Data(HANDLE key, IN PWSTR name,IN ULONG Type , IN PVOID  Data,IN ULONG  DataSize)
{
	NTSTATUS						Status;
	UNICODE_STRING					uname;

	DBG_ENTER(("\"%ws", name));

	RtlInitUnicodeString(&uname, name);

	Status = ZwSetValueKey(key,&uname,0,Type,Data,DataSize);
	if(! NT_SUCCESS(Status)) {
		DBG_LEAVE(("%x", Status));
		return Status;
	}
	
	DBG_LEAVE(("STATUS_SUCCESS"));
	return Status;

}


NTSTATUS RBC9_Set_DWORD(HANDLE key , IN PWSTR name, IN LONG val)
{
	NTSTATUS						Status;

	// DBG_ENTER(("\"%ws\" %p, %u", name, *val, def_val));

	Status = RBC9_Set_Data(key, name,REG_DWORD, &val, sizeof(LONG));
	if(! NT_SUCCESS(Status)) {
		DBG_LEAVE(("%x", Status));
		return Status;
	}

	// DBG_LEAVE(("STATUS_SUCCESS: %u", *val));
	return STATUS_SUCCESS;
}

NTSTATUS RBC9_Set_BINARY(HANDLE key , IN PWSTR name, IN PVOID  Data,IN ULONG  DataSize)
{
	NTSTATUS						Status;

	// DBG_ENTER(("\"%ws\" %p, %u", name, *val, def_val));

	Status = RBC9_Set_Data(key, name,REG_BINARY, Data, DataSize);
	if(! NT_SUCCESS(Status)) {
		DBG_LEAVE(("%x", Status));
		return Status;
	}

	// DBG_LEAVE(("STATUS_SUCCESS: %u", *val));
	return STATUS_SUCCESS;
}



NTSTATUS RBC9_Get_Data(HANDLE key, IN PWSTR name, OUT PKEY_VALUE_PARTIAL_INFORMATION *val)
{
	UNICODE_STRING					uname;
	PKEY_VALUE_PARTIAL_INFORMATION	val_info;
	ULONG							size;
	NTSTATUS						Status;

	//   DBG_ENTER(("\"%ws %p", name, val));

	RtlInitUnicodeString(&uname, name);


	/* query size of data */
	Status = ZwQueryValueKey(key, &uname,
		KeyValuePartialInformation, NULL, 0,
		&size);
	if(! NT_SUCCESS(Status) && Status != STATUS_BUFFER_TOO_SMALL) {
		*val = NULL;
		DBG_LEAVE(("%x", Status));
		return Status;
	}

	/* allocate for query */
	val_info = (PKEY_VALUE_PARTIAL_INFORMATION)ExAllocatePool(NonPagedPool, size);
	if(val_info == NULL) {
		*val = NULL;
		DBG_LEAVE(("STATUS_INSUFFICIENT_RESOURCES"));
		return STATUS_INSUFFICIENT_RESOURCES;
	}

	/* read data */
	Status = ZwQueryValueKey(key, &uname,
		KeyValuePartialInformation, val_info, size,
		&size);


	if(! NT_SUCCESS(Status)) {
		ExFreePool(val_info);
		*val = NULL;
		DBG_LEAVE(("%x", Status));
		return Status;
	}

	*val = val_info;
	//  DBG_LEAVE(("STATUS_SUCCESS"));
	return STATUS_SUCCESS;
}

NTSTATUS RBC9_Get_DWORD(HANDLE key , IN PWSTR name, OUT PLONG val, IN ULONG def_val)
{
	PKEY_VALUE_PARTIAL_INFORMATION	val_info;
	NTSTATUS						Status;

	//DBG_ENTER(("\"%ws\" %p, %u", name, *val, def_val));

	Status = RBC9_Get_Data(key, name, &val_info);
	if(! NT_SUCCESS(Status)) {
		*val = def_val;
		DBG_LEAVE(("%x, %u", Status, *val));
		return Status;
	}

	if(val_info->Type != REG_DWORD || val_info->DataLength != sizeof(LONG)) {
		ExFreePool(val_info);
		*val = def_val;
		DBG_LEAVE(("STATUS_UNSUCCESSFUL, %u", *val));
		return STATUS_UNSUCCESSFUL;
	}

	*val = *((LONG *)val_info->Data);

	ExFreePool(val_info);

	// DBG_LEAVE(("STATUS_SUCCESS: %u", *val));
	return STATUS_SUCCESS;
}


NTSTATUS RBC9_Get_STRING(HANDLE key , IN PWSTR name, OUT PWCHAR val, IN ULONG size)
{
	PKEY_VALUE_PARTIAL_INFORMATION	val_info;
	NTSTATUS						Status;

	//  DBG_ENTER(("%ws", name));

	RtlZeroMemory(val,size);

	Status = RBC9_Get_Data(key, name, &val_info);
	if(! NT_SUCCESS(Status)) {
		DBG_LEAVE(("Error Get Data %x", Status));
		return Status;
	}

	if(val_info->Type != REG_SZ)
	{
		ExFreePool(val_info);
		DBG_LEAVE(("STATUS_UNSUCCESSFUL"));
		return STATUS_UNSUCCESSFUL;
	}
	RtlCopyMemory(val, val_info->Data, (val_info->DataLength <(size-2) ) ? val_info->DataLength : (size-2));

	//	DBG_OUT(("Lentgh %d",val_info->DataLength));
	ExFreePool(val_info);

	//   DBG_LEAVE(("STATUS_SUCCESS"));
	return STATUS_SUCCESS;
}

NTSTATUS RBC9_Get_BINARY(HANDLE key , IN PWSTR name, OUT PVOID val, IN ULONG size)
{
	PKEY_VALUE_PARTIAL_INFORMATION	val_info;
	NTSTATUS						Status;

	//  DBG_ENTER(("%ws", name));

	RtlZeroMemory(val,size);

	Status = RBC9_Get_Data(key, name, &val_info);
	if(! NT_SUCCESS(Status)) {
		DBG_LEAVE(("Error Get Data %x", Status));
		return Status;
	}

	if(val_info->Type != REG_BINARY)
	{
		ExFreePool(val_info);
		DBG_LEAVE(("STATUS_UNSUCCESSFUL"));
		return STATUS_UNSUCCESSFUL;
	}
	RtlCopyMemory(val, val_info->Data, (val_info->DataLength <size ) ? val_info->DataLength : size);

	//DBG_OUT(("Lentgh %d",val_info->DataLength));
	ExFreePool(val_info);

	//   DBG_LEAVE(("STATUS_SUCCESS"));
	return STATUS_SUCCESS;
}



#include "RBC9-SpaceNav.h"
#pragma warning(disable : 4996)
#pragma PAGEDCODE

UNICODE_STRING			InitRegPath;

NTSTATUS DriverEntry(
					 IN OUT PDRIVER_OBJECT   DriverObject,
					 IN PUNICODE_STRING      RegistryPath
					 )
{	


	NTSTATUS Status = STATUS_UNSUCCESSFUL;
	HID_MINIDRIVER_REGISTRATION hidMinidriverRegistration;

	DBG_ENTER(("RBC9-SpaceNav"));


	DriverObject->MajorFunction[IRP_MJ_CREATE]					=	RBC9_DispatchCreateClose;
	DriverObject->MajorFunction[IRP_MJ_CLOSE]					=	RBC9_DispatchCreateClose;
	DriverObject->MajorFunction[IRP_MJ_PNP]						=	RBC9_DispatchPnp;
	DriverObject->MajorFunction[IRP_MJ_POWER]					=	RBC9_DispatchPower;
	DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL]			=	RBC9_DispatchDevice;
	DriverObject->MajorFunction[IRP_MJ_SYSTEM_CONTROL]			=	RBC9_DispatchSystem;
	DriverObject->MajorFunction[IRP_MJ_INTERNAL_DEVICE_CONTROL] =	RBC9_DispatchIntDevice;
	DriverObject->DriverUnload									=	RBC9_DriverUnload;
	DriverObject->DriverExtension->AddDevice					=	RBC9_AddDevice;


	/* register hid minidriver */
	RtlZeroMemory(&hidMinidriverRegistration, sizeof(hidMinidriverRegistration));
	hidMinidriverRegistration.Revision				=	HID_REVISION;
	hidMinidriverRegistration.DriverObject			=	DriverObject;
	hidMinidriverRegistration.RegistryPath			=	RegistryPath;
	hidMinidriverRegistration.DevicesArePolled		=	FALSE;
	hidMinidriverRegistration.DeviceExtensionSize	=	sizeof(DEVICE_EXTENSION);

	Status = HidRegisterMinidriver(&hidMinidriverRegistration);

	
	InitRegPath.Buffer = (PWSTR) ExAllocatePool(PagedPool, RegistryPath->Length + sizeof(WCHAR));
	InitRegPath.MaximumLength = RegistryPath->Length + sizeof(WCHAR);
	RtlCopyUnicodeString(&InitRegPath, RegistryPath);
	InitRegPath.Buffer[RegistryPath->Length/sizeof(WCHAR)] = 0;

	//	DBG_OUT(("Minidriver Registration %ws", RegistryPath->Buffer));

//	DBG_OUT(("Minidriver Registration BIS  %ws", InitRegPath.Buffer));


	DBG_LEAVE(("%X",Status));

	return Status;
}

#pragma PAGEDCODE
NTSTATUS RBC9_DispatchCreateClose(
								  IN PDEVICE_OBJECT		DeviceObject,
								  IN PIRP					Irp
								  )
{
	//DBG_ENTER(("RBC9_DispatchCreateClose"));
	RBC9_COMPLETE_REQUEST(Irp,0,STATUS_SUCCESS,IO_NO_INCREMENT);
	return STATUS_SUCCESS;
}

#pragma PAGEDCODE
VOID RBC9_DriverUnload(IN PDRIVER_OBJECT DriverObject)
{
	//RBC9_Stop_Notify();

	DBG_ENTER((" ... and leave"));

	return;
}


#pragma PAGEDCODE
NTSTATUS RBC9_AddDevice(IN PDRIVER_OBJECT DriverObject,IN PDEVICE_OBJECT func_dev_obj)
{
	NTSTATUS			Status=STATUS_SUCCESS;
    PDEVICE_OBJECT		pDev_obj;
    PDEVICE_EXTENSION	pDevExt;

	DBG_ENTER(("%p, %p", DriverObject, func_dev_obj));	

    /* device object */
    pDev_obj = func_dev_obj;
    pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
    RtlZeroMemory(pDevExt, sizeof(DEVICE_EXTENSION));

    /* init devxce extension */
	pDevExt->RequestCount = 1 ;

	KeInitializeEvent(&pDevExt->Remove_Event, NotificationEvent, FALSE);

    KeInitializeSpinLock(&pDevExt->Pending_Read_irp_Lock);
    InitializeListHead(&pDevExt->Pending_Read_irp);

    pDevExt->Pnp_State = DEVICE_STATE_STARTING;
	pDevExt->Profil_First = NULL;
	pDevExt->Led = NULL;
	pDevExt->Reset_Input = TRUE;
	pDevExt->ModeConfig = FALSE;

	pDevExt->RegPath.Buffer = (PWSTR) ExAllocatePool(PagedPool, InitRegPath.Length + sizeof(WCHAR));
	pDevExt->RegPath.MaximumLength = InitRegPath.Length + sizeof(WCHAR);
	RtlCopyUnicodeString(&pDevExt->RegPath, &InitRegPath);
	pDevExt->RegPath.Buffer[InitRegPath.Length/sizeof(WCHAR)] = 0;

    pDev_obj->Flags &= ~DO_DEVICE_INITIALIZING;

//	DBG_OUT(("regpath %ws", pDevExt->RegPath.Buffer));

	DBG_LEAVE(("%x", Status));
    return Status;
}

#pragma PAGEDCODE
NTSTATUS RBC9_DispatchPnp(IN PDEVICE_OBJECT pDev_obj, IN PIRP pIrp)
{
	NTSTATUS			Status;
	PDEVICE_EXTENSION	pDevExt;
	PIO_STACK_LOCATION	pStack;
	UCHAR				minor_func;

	DBG_ENTER(("%p, %p", pDev_obj, pIrp));

	Status = STATUS_SUCCESS;

	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	pStack = IoGetCurrentIrpStackLocation(pIrp);
	minor_func = pStack->MinorFunction;

	Status = RBC9_IncRequestCount(pDevExt);
	if(! NT_SUCCESS(Status)) {
		RBC9_COMPLETE_REQUEST(pIrp, 0, Status, IO_NO_INCREMENT);
		DBG_LEAVE(("Error %x", Status));
		return Status;
	}


	//DBG_OUT(("pnp: minor func: %02x", minor_func));

	switch (minor_func)
	{
	case IRP_MN_START_DEVICE:
		{
			Status=RBC9_pnp_start(pDev_obj,pIrp);
			break;
		}

	case IRP_MN_STOP_DEVICE:
		{

			Status=RBC9_pnp_stop(pDev_obj,pIrp);
			break;
		}
	case IRP_MN_SURPRISE_REMOVAL:
		{
			Status=RBC9_pnp_surprise_remove(pDev_obj,pIrp);
			break;
		}
	case IRP_MN_REMOVE_DEVICE:
		{
			Status=RBC9_pnp_remove(pDev_obj,pIrp);
			break;
		}
	case IRP_MN_QUERY_CAPABILITIES:
		{
			Status=RBC9_pnp_capabilities(pDev_obj,pIrp);
			break;
		}
	default:
		{
			//DBG_OUT(("Irp %d %x not supported", minor_func,minor_func));

			IoSkipCurrentIrpStackLocation (pIrp);
			Status = IoCallDriver(GET_LOWER_DEVICE_OBJECT(pDev_obj), pIrp);
			break;
		}
	}

	if(minor_func != IRP_MN_REMOVE_DEVICE) {
		RBC9_DecRequestCount(pDevExt);
	}

	DBG_LEAVE(("%x", Status));
	return Status;
}



#pragma PAGEDCODE
NTSTATUS RBC9_DispatchPower(IN PDEVICE_OBJECT pDev_obj, IN PIRP pIrp)
{
	NTSTATUS			Status;
	PDEVICE_EXTENSION	pDevExt;
	PIO_STACK_LOCATION	pStack;

	//DBG_ENTER(("%p, %p", pDev_obj, pIrp));

	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	pStack = IoGetCurrentIrpStackLocation(pIrp);

	Status = RBC9_IncRequestCount(pDevExt);
	if(! NT_SUCCESS(Status)) {
		RBC9_COMPLETE_REQUEST(pIrp, 0, Status, IO_NO_INCREMENT);
		DBG_LEAVE(("Error %x", Status));
		return Status;
	}


/*	DBG_OUT(("power: minor func: %02x, %u, %u, %u, %u",
		pStack->MinorFunction,
		pStack->Parameters.Power.Type,
		pStack->Parameters.Power.State,
		pStack->Parameters.Power.ShutdownType,
		pStack->Parameters.Power.SystemContext));
*/
	if(pStack->MinorFunction == IRP_MN_SET_POWER &&
		pStack->Parameters.Power.Type == DevicePowerState) {
			if(pStack->Parameters.Power.State.DeviceState != PowerDeviceD0) {
				pDevExt->Pnp_State = DEVICE_STATE_STOPPED;
			}
			
			PoSetPowerState(pDev_obj, DevicePowerState,
				pStack->Parameters.Power.State);
	}

	IoSkipCurrentIrpStackLocation(pIrp);
	PoStartNextPowerIrp(pIrp);
	Status = PoCallDriver(GET_LOWER_DEVICE_OBJECT(pDev_obj), pIrp);

	RBC9_DecRequestCount(pDevExt);

	//DBG_LEAVE(("%x", Status));
	return Status;
}

#pragma PAGEDCODE
NTSTATUS RBC9_DispatchIntDevice(IN PDEVICE_OBJECT pDev_obj, IN PIRP pIrp)
{
	NTSTATUS			Status;
	PDEVICE_EXTENSION	pDevExt;

	DBG_ENTER(("%p, %p", pDev_obj, pIrp));

	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	pIrp->IoStatus.Information = 0;

	Status = RBC9_IncRequestCount(pDevExt);
	if(NT_SUCCESS(Status)) 
	{
		PIO_STACK_LOCATION pStack;
		ULONG ioctl_code;

		pStack = IoGetCurrentIrpStackLocation(pIrp);
		ioctl_code = pStack->Parameters.DeviceIoControl.IoControlCode;

		//DBG_OUT(("inter ioctl: code: %08x", ioctl_code));
		
		switch(ioctl_code)
		{
		case IOCTL_HID_GET_DEVICE_DESCRIPTOR:
			{
				//000b0003
				Status=RBC9_ioctl_get_dev_desc(pDev_obj,pIrp);
				break;
			}
		case IOCTL_HID_GET_DEVICE_ATTRIBUTES:
			{
				//000b0027
				Status=RBC9_ioctl_get_dev_attr(pDev_obj,pIrp);
				break;
			}
		case IOCTL_HID_GET_REPORT_DESCRIPTOR:
			{
				//000b0007
				Status=RBC9_ioctl_get_rep_desc(pDev_obj,pIrp);
				break;
			}
		case IOCTL_HID_READ_REPORT:
			{
				//000b000b
				Status=RBC9_ioctl_read_rep(pDev_obj,pIrp);
				break;
			}
		case IOCTL_HID_WRITE_REPORT:
			{
				
				Status=RBC9_ioctl_write_rep(pDev_obj,pIrp);
				break;
			}

		case IOCTL_HID_SET_OUTPUT_REPORT:
			{
			//	DBG_OUT(("IOCTL_HID_SET_OUTPUT_REPORT %x",ioctl_code));
				Status=RBC9_ioctl_write_rep(pDev_obj,pIrp);
				break;
			}
		case IOCTL_HID_SET_FEATURE:
			{
				//DBG_OUT(("IOCTL_HID_SET_FEATURE %x",ioctl_code));
				Status=RBC9_ioctl_write_rep(pDev_obj,pIrp);
				break;
			}
		default:
			{
			//	DBG_OUT(("inter ioctl: not supported %x",ioctl_code));
				Status=STATUS_NOT_SUPPORTED;
				RBC9_COMPLETE_REQUEST(pIrp, 0, Status, IO_NO_INCREMENT);
				break;
			}
		}

		RBC9_DecRequestCount(pDevExt);
	}

	DBG_LEAVE(("%x", Status));
	return Status;
}
#pragma PAGEDCODE
NTSTATUS RBC9_DispatchDevice(IN PDEVICE_OBJECT pDev_obj, IN PIRP pIrp)
{
	PDEVICE_EXTENSION pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	NTSTATUS Status;
	PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp);
	//DBG_OUT(("RBC9_DispatchDevice - - - -"));
	IoSkipCurrentIrpStackLocation(pIrp);
	Status = IoCallDriver(GET_LOWER_DEVICE_OBJECT(pDev_obj), pIrp);
	return Status;
}

#pragma PAGEDCODE
NTSTATUS RBC9_DispatchSystem(IN PDEVICE_OBJECT pDev_obj, IN PIRP pIrp)
{
	PDEVICE_EXTENSION pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	NTSTATUS Status;
	PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp);
	//DBG_OUT(("RBC9_DispatchSystem - - - -"));
	IoSkipCurrentIrpStackLocation(pIrp);
	Status = IoCallDriver(GET_LOWER_DEVICE_OBJECT(pDev_obj), pIrp);
	return Status;
}

#pragma LOCKEDCODE
NTSTATUS RBC9_IncRequestCount(IN PDEVICE_EXTENSION pDevExt)
{
	NTSTATUS Status;
	LONG cnt;

	//DBG_ENTER(("%p", pDevExt));

	cnt = InterlockedIncrement(&pDevExt->RequestCount);
	//DBG_OUT(("increment ref: %d", cnt));

	if(pDevExt->Pnp_State == DEVICE_STATE_REMOVED) {
		//DBG_OUT(("already removed"));

		cnt = InterlockedDecrement(&pDevExt->RequestCount);
		//DBG_OUT(("decrement ref: %d", cnt));
		if(cnt == 0) {
			KeSetEvent(&pDevExt->Remove_Event, IO_NO_INCREMENT, FALSE);
		}

		Status = STATUS_DELETE_PENDING;
	} else {
		Status = STATUS_SUCCESS;
	}

	//DBG_LEAVE(("%x", Status));
	return Status;
}


VOID RBC9_DecRequestCount(IN PDEVICE_EXTENSION pDevExt)
{
	LONG cnt;

	//DBG_ENTER(("%p", pDevExt));

	cnt = InterlockedDecrement(&pDevExt->RequestCount);
	//DBG_OUT(("decrement ref: %d", cnt));
	if(cnt == 0) {
		KeSetEvent(&pDevExt->Remove_Event, IO_NO_INCREMENT, FALSE);
	}
	//DBG_LEAVE(("void"));
}

#include "RBC9-SpaceNav.h"
#pragma warning(disable : 4996)

NTSTATUS RBC9_usb_start(IN PDEVICE_OBJECT pDev_obj)
{
	NTSTATUS				Status;
	PDEVICE_EXTENSION		pDevExt;

	DBG_ENTER(("%p", pDev_obj));

	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	/* initialize usb */
	Status = RBC9_usb_reset(pDev_obj);
	if(! NT_SUCCESS(Status)) {
		DBG_LEAVE(("%x: usb_reset failed", Status));
		return Status;
	}

	Status = RBC9_usb_get_dev_desc(pDev_obj);
	if(! NT_SUCCESS(Status)) {
		DBG_LEAVE(("%x: usb_get_dev_desc failed", Status));
		return Status;
	}

	Status = RBC9_usb_select_conf(pDev_obj);
	if(! NT_SUCCESS(Status)) {
		DBG_LEAVE(("%x: usb_select_conf failed", Status));
		return Status;
	}

	Status = RBC9_usb_get_hid_desc(pDev_obj);
	if(! NT_SUCCESS(Status)) {
		DBG_LEAVE(("%x: usb_get_hid_desc failed", Status));
		return Status;
	}

	/* ready to start */
	pDevExt->Pnp_State = DEVICE_STATE_STARTED;

	/* start usb worker */
	{
		HANDLE thread;

		/* create thread and start */
		pDevExt->usb_worker_thread_obj = NULL;
		Status = PsCreateSystemThread(&thread,
			THREAD_ALL_ACCESS, NULL, NULL, NULL,
			RBC9_usb_worker, pDev_obj);
		if(! NT_SUCCESS(Status)) {
			DBG_LEAVE(("%x: PsCreateSystemThread failed", Status));
			return Status;
		}

		ObReferenceObjectByHandle(thread, THREAD_ALL_ACCESS, NULL, KernelMode,
			&pDevExt->usb_worker_thread_obj, NULL);
	}


	/* initialize hid part */
	Status = RBC9_hid_start(pDev_obj);
	if(! NT_SUCCESS(Status)) {
		DBG_LEAVE(("%x: hid_start failed", Status));
		return Status;
	}

	DBG_LEAVE(("%x", Status));
	return STATUS_SUCCESS;
}

NTSTATUS RBC9_usb_remove(IN PDEVICE_OBJECT pDev_obj)
{

	PDEVICE_EXTENSION		pDevExt;


	DBG_ENTER(("%p", pDev_obj));

	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);
	

	/* wait for usb worker stop */
	if(pDevExt->usb_worker_thread_obj != NULL) {
		KeWaitForSingleObject(pDevExt->usb_worker_thread_obj,
			Executive, KernelMode, FALSE, NULL);
		ObDereferenceObject(pDevExt->usb_worker_thread_obj);
		pDevExt->usb_worker_thread_obj = NULL;
	}
	/* finalize hid part */
	RBC9_hid_remove(pDev_obj);

	DBG_LEAVE(("STATUS_SUCCESS"));
	return STATUS_SUCCESS;
}


static NTSTATUS RBC9_usb_reset(IN PDEVICE_OBJECT pDev_obj)
{
	NTSTATUS Status;
	ULONG port_status;

	DBG_ENTER(("%p", pDev_obj));

	Status = RBC9_usb_get_port_status(pDev_obj, &port_status);
	if(! NT_SUCCESS(Status)) {
		DBG_LEAVE(("%x: usb_get_port_status failed", Status));
		return Status;
	}

	/* not connected */
	if((port_status & USBD_PORT_CONNECTED) == 0) {
		DBG_LEAVE(("STATUS_NO_SUCH_DEVICE"));
		return STATUS_NO_SUCH_DEVICE;
	}

	/* already enabled */
	if((port_status & USBD_PORT_ENABLED) != 0) {
		//DBG_LEAVE(("STATUS_SUCCESS"));
		return STATUS_SUCCESS;
	}

	/* reset port */
	Status = RBC9_usb_reset_port(pDev_obj);
	if(! NT_SUCCESS(Status)) {
		DBG_LEAVE(("%x: usb_reset_port failed", Status));
		return Status;
	}

	Status = RBC9_usb_get_port_status(pDev_obj, &port_status);
	if(! NT_SUCCESS(Status)) {
		DBG_LEAVE(("%x: usb_get_port_status failed", Status));
		return Status;
	}

	if((port_status & USBD_PORT_CONNECTED) == 0 ||
		(port_status & USBD_PORT_ENABLED) == 0) {
			DBG_LEAVE(("STATUS_NO_SUCH_DEVICE"));
			return STATUS_NO_SUCH_DEVICE;
	}

	DBG_LEAVE(("STATUS_SUCCESS"));
	return STATUS_SUCCESS;
}

static NTSTATUS RBC9_usb_get_port_status(IN PDEVICE_OBJECT pDev_obj,OUT ULONG *port_status)
{
	NTSTATUS Status;
//	DBG_ENTER(("%p, %u", pDev_obj, *port_status));

	Status = RBC9_usb_call(pDev_obj, IOCTL_INTERNAL_USB_GET_PORT_STATUS,port_status, NULL);

//	DBG_LEAVE(("%x", Status));
	return Status;
}

static NTSTATUS RBC9_usb_call(IN PDEVICE_OBJECT pDev_obj, IN ULONG ioctl_code, IN PVOID arg1, IN PVOID arg2)
{
	IO_STATUS_BLOCK io_status;
	PIRP pIrp;
	PIO_STACK_LOCATION pStack;
	KEVENT evt;
	NTSTATUS Status;

	//DBG_ENTER(("%p, %u, %p, %p", pDev_obj, ioctl_code, arg1, arg2));

	KeInitializeEvent(&evt, NotificationEvent, FALSE);

	pIrp = IoBuildDeviceIoControlRequest(ioctl_code,
		GET_LOWER_DEVICE_OBJECT(pDev_obj),
		NULL, 0,
		NULL, 0,
		TRUE,
		&evt, &io_status);

	pStack = IoGetNextIrpStackLocation(pIrp);
	pStack->Parameters.Others.Argument1 = arg1;
	pStack->Parameters.Others.Argument2 = arg2;

	Status = IoCallDriver(GET_LOWER_DEVICE_OBJECT(pDev_obj), pIrp);
	if(Status == STATUS_PENDING) {
		//DBG_OUT(("STATUS_PENDING"));
		KeWaitForSingleObject(&evt, Executive, KernelMode, FALSE, NULL);
		Status = io_status.Status;
	}

	//DBG_LEAVE(("%x", Status));
	return Status;
}

static NTSTATUS RBC9_usb_reset_port(IN PDEVICE_OBJECT pDev_obj)
{
	NTSTATUS Status;

	//DBG_ENTER(("%p", pDev_obj));

	Status = RBC9_usb_call(pDev_obj, IOCTL_INTERNAL_USB_RESET_PORT, NULL, NULL);

	//DBG_LEAVE(("%x", Status));
	return Status;
}



static NTSTATUS RBC9_usb_get_dev_desc(IN PDEVICE_OBJECT pDev_obj)
{
	NTSTATUS				Status;
	PDEVICE_EXTENSION		pDevExt;
	PURB					urb;

	DBG_ENTER(("%p", pDev_obj));

	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	urb = (PURB)ExAllocatePool(NonPagedPool, sizeof(struct _URB_CONTROL_DESCRIPTOR_REQUEST));
	if(urb == NULL) {
		DBG_LEAVE(("urb STATUS_INSUFFICIENT_RESOURCES"));
		return STATUS_INSUFFICIENT_RESOURCES;
	}

	UsbBuildGetDescriptorRequest(urb, sizeof(struct _URB_CONTROL_DESCRIPTOR_REQUEST),
		USB_DEVICE_DESCRIPTOR_TYPE, 0, 0,
		&pDevExt->DeviceDescriptor, NULL, sizeof(USB_DEVICE_DESCRIPTOR),
		NULL);

	Status = RBC9_usb_call(pDev_obj, IOCTL_INTERNAL_USB_SUBMIT_URB, urb, NULL);
	if(! NT_SUCCESS(Status) || ! USBD_SUCCESS(urb->UrbHeader.Status)) {
		ExFreePool(urb);
		DBG_LEAVE(("STATUS_UNSUCCESSFUL"));
		return STATUS_UNSUCCESSFUL;
	}

	pDevExt->usb_control_pipe = urb->UrbControlTransfer.PipeHandle;

	ExFreePool(urb);

	DBG_OUT(("VendorID %X, ProductID %X, Version %X ", pDevExt->DeviceDescriptor.idVendor, pDevExt->DeviceDescriptor.idProduct, pDevExt->DeviceDescriptor.bcdDevice  ));
	DBG_LEAVE(("%x", Status));

	return Status;
}

static NTSTATUS RBC9_usb_select_conf(IN PDEVICE_OBJECT pDev_obj)
{
	NTSTATUS						Status;
	PDEVICE_EXTENSION				pDevExt;
	PUSB_CONFIGURATION_DESCRIPTOR	conf_desc;
	PUSB_INTERFACE_DESCRIPTOR		id;
	USBD_INTERFACE_LIST_ENTRY		iface_list[5];
	PURB							urb;
	PUSBD_INTERFACE_INFORMATION		iface_info;
	PUSBD_PIPE_INFORMATION			pipe_info;
	ULONG							size;

	DBG_ENTER(("%p", pDev_obj));

	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	Status = RBC9_usb_get_conf_desc(pDev_obj, &conf_desc, &size, 0);
	if(! NT_SUCCESS(Status)) {

		DBG_LEAVE(("%x: usb_get_conf_desc failed", Status));
		return Status;
	}

	id = USBD_ParseConfigurationDescriptorEx(conf_desc, conf_desc, -1, -1, -1, -1, -1);
	if(id == NULL) {
		ExFreePool(conf_desc);
		DBG_LEAVE(("USBD_ParseConfigurationDescriptorEx STATUS_NO_SUCH_DEVICE"));
		return STATUS_NO_SUCH_DEVICE;
	}
/*
	DBG_OUT(("USB_INTERFACE_DESCRIPTOR"));
	DBG_INFO(("bLength %x",id->bLength));
	DBG_INFO(("bDescriptorType  %x %x",id->bDescriptorType ));
	DBG_INFO(("bInterfaceNumber  %x",id->bInterfaceNumber ));
	DBG_INFO(("bAlternateSetting  %x",id->bAlternateSetting ));
	DBG_INFO(("bNumEndpoints   %x",id->bNumEndpoints  ));
	DBG_INFO(("bInterfaceClass   %x",id->bInterfaceClass  ));
	DBG_INFO(("bInterfaceSubClass  %x",id->bInterfaceSubClass ));
	DBG_INFO(("bInterfaceProtocol  %x",id->bInterfaceProtocol ));
	DBG_INFO(("iInterface  %x",id->iInterface ));
	DBG_INFO((""));
*/
	iface_list[0].InterfaceDescriptor = id;
	iface_list[0].Interface =NULL;
	iface_list[1].InterfaceDescriptor = NULL;

//	DBG_OUT(("Selecting the configuration"));
	urb = USBD_CreateConfigurationRequestEx(conf_desc, iface_list);

	Status = RBC9_usb_call(pDev_obj, IOCTL_INTERNAL_USB_SUBMIT_URB, urb, NULL);
	if(! NT_SUCCESS(Status) || ! USBD_SUCCESS(urb->UrbHeader.Status)) {
		ExFreePool(urb);
		ExFreePool(conf_desc);
		DBG_LEAVE(("USBD_CreateConfigurationRequestEx STATUS_UNSUCCESSFUL"));
		return STATUS_UNSUCCESSFUL;
	}

	pDevExt->usb_conf_handle = urb->UrbSelectConfiguration.ConfigurationHandle;
	iface_info = &urb->UrbSelectConfiguration.Interface;
/*	DBG_OUT(("Interface: InterfaceNumber %u, AlternateSetting %u, Class %u, SubClass %u, Protocol %u, NumberOfPipes %u",
		iface_info->InterfaceNumber, iface_info->AlternateSetting,
		iface_info->Class, iface_info->SubClass,
		iface_info->Protocol, iface_info->NumberOfPipes));
*/

	pDevExt->usb_input_pipe = NULL;
	pDevExt->usb_output_pipe = NULL;

	switch (iface_info->NumberOfPipes)
	{
	case 2:
		{
			pipe_info = &iface_info->Pipes[0];
			pDevExt->usb_input_pipe = pipe_info->PipeHandle;

			DBG_OUT(("Pipe 0 : MaxTransfer %d, MaxPckSize %d, PipeType %d, Interval %d, Handle %d Address %d", 
				pipe_info->MaximumTransferSize, pipe_info->MaximumPacketSize, 
				pipe_info->PipeType, pipe_info->Interval, 
				pipe_info->PipeHandle, pipe_info->EndpointAddress));

			pipe_info = &iface_info->Pipes[1];
			pDevExt->usb_output_pipe = pipe_info->PipeHandle;

			DBG_OUT(("Pipe 1 : MaxTransfer %d, MaxPckSize %d, PipeType %d, Interval %d, Handle %d Address %d", 
				pipe_info->MaximumTransferSize, pipe_info->MaximumPacketSize, 
				pipe_info->PipeType, pipe_info->Interval, 
				pipe_info->PipeHandle, pipe_info->EndpointAddress));
			break;
		}
	case 1:
		{
			pipe_info = &iface_info->Pipes[0];
			pDevExt->usb_input_pipe = pipe_info->PipeHandle;

	/*		DBG_OUT(("Pipe 0 : MaxTransfer %d, MaxPckSize %d, PipeType %d, Interval %d, Handle %d Address %d", 
				pipe_info->MaximumTransferSize, pipe_info->MaximumPacketSize, 
				pipe_info->PipeType, pipe_info->Interval, 
				pipe_info->PipeHandle, pipe_info->EndpointAddress));
		*/	break;
		}
	default:
		{
			DBG_OUT(("No Additionnal Pipe - Only Cntrol Pipe"));
		}
	}


	ExFreePool(urb);
	ExFreePool(conf_desc);

	DBG_LEAVE(("STATUS_SUCCESS"));
	return STATUS_SUCCESS;
}
static NTSTATUS RBC9_usb_get_conf_desc(IN PDEVICE_OBJECT pDev_obj,
									   OUT PUSB_CONFIGURATION_DESCRIPTOR *conf_desc,
									   OUT ULONG *size,
									   IN UCHAR conf_idx)
{
	NTSTATUS						Status;
	ULONG							desc_size;
	PURB							urb;
	PUSB_CONFIGURATION_DESCRIPTOR	desc;

	DBG_ENTER(("%p, %p, %u, %u", pDev_obj, conf_desc, *size, conf_idx));

	urb = (PURB)ExAllocatePool(NonPagedPool, sizeof(struct _URB_CONTROL_DESCRIPTOR_REQUEST));
	if(urb == NULL) {
		DBG_LEAVE(("urb STATUS_INSUFFICIENT_RESOURCES"));
		return STATUS_INSUFFICIENT_RESOURCES;
	}

	desc = (PUSB_CONFIGURATION_DESCRIPTOR)ExAllocatePool(NonPagedPool, sizeof(USB_CONFIGURATION_DESCRIPTOR));
	if(desc == NULL) {
		ExFreePool(urb);
		DBG_LEAVE(("desc STATUS_INSUFFICIENT_RESOURCES"));
		return STATUS_INSUFFICIENT_RESOURCES;
	}
	DBG_OUT(("RBC9_usb_get_conf_desc - getting configuration descriptor Part 1"));
	UsbBuildGetDescriptorRequest(urb, sizeof(struct _URB_CONTROL_DESCRIPTOR_REQUEST),
		USB_CONFIGURATION_DESCRIPTOR_TYPE,
		conf_idx, 0,
		desc, NULL, sizeof(USB_CONFIGURATION_DESCRIPTOR),
		NULL);

	Status = RBC9_usb_call(pDev_obj, IOCTL_INTERNAL_USB_SUBMIT_URB, urb, NULL);
	if(! NT_SUCCESS(Status) || ! USBD_SUCCESS(urb->UrbHeader.Status)) {
		ExFreePool(urb);
		ExFreePool(desc);
		DBG_LEAVE(("STATUS_UNSUCCESSFUL descriptor 1"));
		return STATUS_UNSUCCESSFUL;
	}

	desc_size = desc->wTotalLength;
	ExFreePool(desc);
	desc = (PUSB_CONFIGURATION_DESCRIPTOR)ExAllocatePool(NonPagedPool, desc_size + 16); /* TODO: what is 16 ? */
	if(desc == NULL) {
		ExFreePool(urb);
		DBG_LEAVE(("descriptor 2 STATUS_INSUFFICIENT_RESOURCES"));
		return STATUS_INSUFFICIENT_RESOURCES;
	}

	DBG_OUT(("Getting second part of configuration descriptor"));
	UsbBuildGetDescriptorRequest(urb, sizeof(struct _URB_CONTROL_DESCRIPTOR_REQUEST),
		USB_CONFIGURATION_DESCRIPTOR_TYPE,
		conf_idx, 0,
		desc, NULL, desc_size,
		NULL);

	Status = RBC9_usb_call(pDev_obj, IOCTL_INTERNAL_USB_SUBMIT_URB, urb, NULL);
	if(! NT_SUCCESS(Status) || ! USBD_SUCCESS(urb->UrbHeader.Status)) {
		ExFreePool(urb);
		ExFreePool(desc);
		DBG_LEAVE(("STATUS_UNSUCCESSFUL"));
		return STATUS_UNSUCCESSFUL;
	}

	*size = urb->UrbControlDescriptorRequest.TransferBufferLength;
	*conf_desc = desc;

//	DBG_OUT(("USB_CONFIGURATION_DESCRIPTOR \nbLength %x \nbDescriptorType  %x \nwTotalLength %x \nbNumInterfaces %x \niConfiguration  %x \nbConfigurationValue %x",
//		desc->bLength ,desc->bDescriptorType  ,desc->wTotalLength  ,desc->bNumInterfaces  ,desc->iConfiguration  ,desc->bConfigurationValue ));

	ExFreePool(urb);

	DBG_LEAVE(("STATUS_SUCCESS"));
	return STATUS_SUCCESS;
}
static NTSTATUS RBC9_usb_get_hid_desc(IN PDEVICE_OBJECT pDev_obj)
{
	NTSTATUS				Status;
	PDEVICE_EXTENSION		pDevExt	= GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	UCHAR					*BufDesc;
	ULONG					BufSize;

	DBG_ENTER(("%p", pDev_obj));

	BufSize = 999;

	BufDesc = (UCHAR *)ExAllocatePool(NonPagedPool, BufSize);
	if(BufDesc == NULL) {
		DBG_LEAVE(("BufDesc STATUS_INSUFFICIENT_RESOURCES"));
		return STATUS_INSUFFICIENT_RESOURCES;
	}

	Status = RBC9_usb_get_control_transfer(pDev_obj, BufDesc, &BufSize,NAV_PACKET_DESCRIPTOR);
	if(!NT_SUCCESS(Status)) 
	{
		ExFreePool(BufDesc);
		DBG_LEAVE(("STATUS_UNSUCCESSFUL"));
		return STATUS_UNSUCCESSFUL;
	}

	pDevExt->Size_HID_Report_Space = (USHORT) BufSize;
	pDevExt->HID_Report_Space = (UCHAR *)ExAllocatePool(NonPagedPool, BufSize);
	RtlCopyMemory(pDevExt->HID_Report_Space, BufDesc, BufSize);

	
	DBG_OUT(("Report Space %d",BufSize));

	ExFreePool(BufDesc);
	
	DBG_LEAVE(("%x", Status));

	return Status;
}

#pragma PAGEDCODE
static VOID RBC9_usb_worker(IN PVOID ctxt)
{
	PDEVICE_OBJECT				pDev_obj;
	PDEVICE_EXTENSION			pDevExt;
	RAW_INPUT buf;
	ULONG buf_size;


	pDev_obj = (PDEVICE_OBJECT)ctxt;
	pDevExt = GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj);

	DBG_ENTER(("%p - DEVICE_STATE_STARTED 1 = %d ?", ctxt,pDevExt->Pnp_State));

	KeSetPriorityThread(KeGetCurrentThread(), LOW_REALTIME_PRIORITY);

	while(pDevExt->Pnp_State == DEVICE_STATE_STARTED) {
		NTSTATUS Status;

		/* read from usb */
		buf_size = sizeof(buf);
		RtlZeroMemory(&buf, buf_size);

		Status = RBC9_usb_get_interrupt_transfer(pDev_obj, &buf, &buf_size);
		if(! NT_SUCCESS(Status)) 
		{
		//	DBG_OUT(("RBC9_usb_worker - get interrupt fail: %x", Status));
			buf = pDevExt->hwInData;

			{
				LARGE_INTEGER time;

				time.QuadPart = -10 * 1000 * 10;
				KeDelayExecutionThread(KernelMode, FALSE, &time);
			}
		}

		/* set raw input */
		pDevExt->hwInData = buf;

		//	DBG_OUT(("RBC9_usb_worker - ReportId %x",pDevExt->hwInData.ReportId));

		/* indicate to process data */
		KeSetEvent(&pDevExt->hid_worker_wakeup_event, IO_NO_INCREMENT, FALSE);
	}

	//DBG_OUT(("already stop/removed"));

	DBG_LEAVE(("STATUS_SUCCESS"));
	PsTerminateSystemThread(STATUS_SUCCESS);
}


#pragma LOCKEDCODE
NTSTATUS RBC9_usb_get_interrupt_transfer(IN PDEVICE_OBJECT pDev_obj, IN PVOID buf, ULONG *buf_size)
{
	// DBG_ENTER((" and leave: %p, %p, %u", pDev_obj, buf, *buf_size));
	return RBC9_usb_interrupt_transfer(pDev_obj, buf, buf_size,
		GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj)->usb_input_pipe,
		(USBD_TRANSFER_DIRECTION_IN |
		USBD_SHORT_TRANSFER_OK));
}

NTSTATUS RBC9_usb_put_interrupt_transfer(IN PDEVICE_OBJECT pDev_obj, IN PVOID buf, ULONG *buf_size)
{
//	DBG_ENTER((" and leave: %p, %p, %u", pDev_obj, buf, *buf_size));
	return RBC9_usb_interrupt_transfer(pDev_obj, buf, buf_size,
		GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj)->usb_output_pipe,
		0 );
}

NTSTATUS RBC9_usb_put_control_transfer(IN PDEVICE_OBJECT pDev_obj, IN PVOID buf, ULONG *buf_size, IN PVOID packet)
{
	//DBG_ENTER((" and leave: %p, %p, %u", pDev_obj, buf, *buf_size));
	return RBC9_usb_control_transfer(pDev_obj, buf, buf_size,
		GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj)->usb_control_pipe,
		(USBD_DEFAULT_PIPE_TRANSFER|
		USBD_SHORT_TRANSFER_OK), packet );
}

NTSTATUS RBC9_usb_get_control_transfer(IN PDEVICE_OBJECT pDev_obj, IN PVOID buf, ULONG *buf_size, IN PVOID packet)
{
	DBG_ENTER((" and leave: %p, %p, %u", pDev_obj, buf, *buf_size));
	return RBC9_usb_control_transfer(pDev_obj, buf, buf_size,
		GET_MINIDRIVER_DEVICE_EXTENSION(pDev_obj)->usb_control_pipe,
		(USBD_TRANSFER_DIRECTION_IN |
		USBD_DEFAULT_PIPE_TRANSFER|
		USBD_SHORT_TRANSFER_OK), packet );
}

static NTSTATUS RBC9_usb_control_transfer(IN PDEVICE_OBJECT pDev_obj,
												IN PVOID buf, ULONG *buf_size,
												USBD_PIPE_HANDLE pipe, ULONG flags, IN PVOID packet)
{
	PURB urb;
	NTSTATUS Status;

	//DBG_ENTER(("%p, %p, %u, %p, %u", pDev_obj, buf, *buf_size, pipe, flags));

	if(pipe == NULL) {
		DBG_LEAVE(("STATUS_INVALID_HANDLE"));
		return STATUS_INVALID_HANDLE;
	}

	if(buf == NULL || *buf_size < 1) {
		DBG_LEAVE(("STATUS_INVALID_PARAMETER"));
		return STATUS_INVALID_PARAMETER;
	}

	urb = (PURB)ExAllocatePool(NonPagedPool, sizeof(struct _URB_CONTROL_TRANSFER));
	if(urb == NULL) {
		DBG_LEAVE(("STATUS_INSUFFICIENT_RESOURCES"));
		return STATUS_INSUFFICIENT_RESOURCES;
	}

	RtlZeroMemory(urb, sizeof(struct _URB_CONTROL_TRANSFER));


	urb->UrbControlTransfer.Hdr.Function			= URB_FUNCTION_CONTROL_TRANSFER;
	urb->UrbControlTransfer.Hdr.Length				= sizeof(struct _URB_CONTROL_TRANSFER);
	urb->UrbControlTransfer.Hdr.Status				= 0;
	urb->UrbControlTransfer.PipeHandle				= 0;
	urb->UrbControlTransfer.TransferFlags 			= flags;
	urb->UrbControlTransfer.TransferBufferLength 	= *buf_size;
	urb->UrbControlTransfer.TransferBuffer 			= buf;
	urb->UrbControlTransfer.TransferBufferMDL 		= NULL;
	urb->UrbControlTransfer.UrbLink 				= NULL;
	
	RtlCopyMemory(urb->UrbControlTransfer.SetupPacket, packet, 8);

	Status = RBC9_usb_call(pDev_obj, IOCTL_INTERNAL_USB_SUBMIT_URB, urb, NULL);
	
	*buf_size = urb->UrbControlTransfer.TransferBufferLength;

//	DBG_OUT(("Buf Len %x",urb->UrbControlTransfer.TransferBufferLength));

	if(! NT_SUCCESS(Status) || ! USBD_SUCCESS(urb->UrbHeader.Status)) {
		ExFreePool(urb);
		DBG_LEAVE(("STATUS_UNSUCCESSFUL"));
		return STATUS_UNSUCCESSFUL;
	}

	ExFreePool(urb);

	// DBG_LEAVE(("STATUS_SUCCESS"));
	return STATUS_SUCCESS;
}



static NTSTATUS RBC9_usb_interrupt_transfer(IN PDEVICE_OBJECT pDev_obj,
											IN PVOID buf, ULONG *buf_size,
											USBD_PIPE_HANDLE pipe, ULONG flags)
{
	PURB urb;
	NTSTATUS Status;

	//DBG_ENTER(("%p, %p, %u, %p, %u", pDev_obj, buf, *buf_size, pipe, flags));

	if(pipe == NULL) {
		DBG_LEAVE(("STATUS_INVALID_HANDLE"));
		return STATUS_INVALID_HANDLE;
	}

	if(buf == NULL || *buf_size < 1) {
		DBG_LEAVE(("STATUS_INVALID_PARAMETER"));
		return STATUS_INVALID_PARAMETER;
	}

	urb = (PURB)ExAllocatePool(NonPagedPool, sizeof(struct _URB_BULK_OR_INTERRUPT_TRANSFER));
	if(urb == NULL) {
		DBG_LEAVE(("STATUS_INSUFFICIENT_RESOURCES"));
		return STATUS_INSUFFICIENT_RESOURCES;
	}

	UsbBuildInterruptOrBulkTransferRequest(urb, sizeof(struct _URB_BULK_OR_INTERRUPT_TRANSFER),
		pipe,
		buf, NULL, *buf_size,
		flags,
		NULL);
	Status = RBC9_usb_call(pDev_obj, IOCTL_INTERNAL_USB_SUBMIT_URB, urb, NULL);
	if(! NT_SUCCESS(Status) || ! USBD_SUCCESS(urb->UrbHeader.Status)) {
		ExFreePool(urb);
	//	DBG_LEAVE(("STATUS_UNSUCCESSFUL"));
		return STATUS_UNSUCCESSFUL;
	}

	*buf_size = urb->UrbBulkOrInterruptTransfer.TransferBufferLength;

	ExFreePool(urb);

	// DBG_LEAVE(("STATUS_SUCCESS"));
	return STATUS_SUCCESS;
}

// Automatically created file! 
#define DRIVER_VERSION_BUILD 1074 
 
///////////////////////////////////////////////////////////////////////////////
///
/// Useful macros for driver writers.
///
/// PUBLIC DOMAIN
///
///////////////////////////////////////////////////////////////////////////////

// $Id$

#pragma once

#define _ANSISTRING(text) #text
#define ANSISTRING(text) _ANSISTRING(text)

#define _WIDESTRING(text) L##text
#define WIDESTRING(text) _WIDESTRING(text)

#define PRESET_UNICODE_STRING(symbol, buffer) \
        UNICODE_STRING symbol = \
            { \
            sizeof(WIDESTRING(buffer)) - sizeof(WCHAR), \
            sizeof(WIDESTRING(buffer)), \
            WIDESTRING(buffer) \
            };

#define CREATE_XVER(maj,min,build) maj ## , ## min ## , 0, ## build
#define CREATE_FVER(maj,min,build) maj ## . ## min ## .0. ## build
#define CREATE_PVER(maj,min,build) maj ## . ## min

#if DBG
	#ifdef ADVANCED_DEBUG
	#define DebugPrint DbgPrint("[%s] %s (line: %d)\n", __##FILE##__, __##FUNCTION##__, __##LINE##__); DbgPrint
	#else
	#define DebugPrint DbgPrint
	#endif
#else
#define DebugPrint /##/DbgPrint
#endif
///////////////////////////////////////////////////////////////////////////////
///
/// Defines for the version information in the resource file
///
/// PUBLIC DOMAIN
///
///////////////////////////////////////////////////////////////////////////////

// $Id$

#pragma once
#include "buildnumber.h"

// ---------------------------------------------------------------------------
// Several defines have to be given before including this file. These are:
// ---------------------------------------------------------------------------
#define TEXT_AUTHOR            [RBC9-X11] // author (optional value)
#define PRD_MAJVER             1 // major prodduct version
#define PRD_MINVER             0 // minor product version
#define PRD_BUILD              0 // build number for product
#define DRV_MAJVER             2 // major driver version
#define DRV_MINVER             1 // minor driver version
#define DRV_BUILD              DRIVER_VERSION_BUILD // build number for driver
#define DRV_YEAR               2006 // current year
#define TEXT_WEBSITE           http:/##/RBC9.NO-IP.COM // website
#define TEXT_PRODUCTNAME       RBC9 Space Navigator // product's name
#define TEXT_FILEDESC          what 3dconn should have done // component description
#define TEXT_COMPANY           [RBC9-X11] // company
#define TEXT_MODULE            RBC9-SpaceNav // module name
#define TEXT_COPYRIGHT         Copyright \xA9 DRV_YEAR TEXT_COMPANY // copyright information
// #define TEXT_SPECIALBUILD      // optional comment for special builds
#define TEXT_INTERNALNAME      RBC9-SpaceNav.sys // copyright information
// #define TEXT_COMMENTS          // optional comments
// ---------------------------------------------------------------------------
// ... well, that's it. Pretty self-explanatory ;)
// ---------------------------------------------------------------------------


#include <usbdrivr.h>
#include <HIDPORT.H>



#define GET_MINIDRIVER_DEVICE_EXTENSION(DO)  \
	((PDEVICE_EXTENSION) (((PHID_DEVICE_EXTENSION)(DO)->DeviceExtension)->MiniDeviceExtension))

#define GET_LOWER_DEVICE_OBJECT(DO) (((PHID_DEVICE_EXTENSION) ((DO)->DeviceExtension)) \
	->NextDeviceObject)

#define GET_PHYSICAL_DEVICE_OBJECT(DO) (((PHID_DEVICE_EXTENSION) ((DO)->DeviceExtension)) \
	->PhysicalDeviceObject)


typedef enum _DEVICE_PNP_STATE {
	DEVICE_STATE_STARTING,
	DEVICE_STATE_STARTED,
	DEVICE_STATE_STOPPED,
	DEVICE_STATE_REMOVED,
	DEVICE_STATE_UNKNOWN
} DEVICE_PNP_STATE;


/* device extension */
typedef struct _DEVICE_EXTENSION{

	/* flags */
	DEVICE_PNP_STATE		Pnp_State;

	short					Profil_Id;
	PPROFIL					Profil_Actif;
	PPROFIL					Profil_First;

	/*	Reset Axe , btn , Key , mouse */
	BOOLEAN					Reset_Input;
	BOOLEAN					ModeConfig;

	/* request count */
	LONG					RequestCount;

	/* remove event */
	KEVENT					Remove_Event;

	/* pending read report request */
	LIST_ENTRY				Pending_Read_irp;
	KSPIN_LOCK				Pending_Read_irp_Lock;

	/* Physical Device Descriptor */
	USB_DEVICE_DESCRIPTOR	DeviceDescriptor;

	/* usb handles */
	USBD_CONFIGURATION_HANDLE	usb_conf_handle;
	USBD_PIPE_HANDLE			usb_input_pipe;
	USBD_PIPE_HANDLE			usb_output_pipe;
	USBD_PIPE_HANDLE			usb_control_pipe;
	PVOID						usb_worker_thread_obj;

	/* USB Data */

	CONTROLLER_INPUT_REPORT		input_state;

	RAW_INPUT				hwInData;
	
	KEYB_STATUS				KeyB;
	MOU_REPEAT				Mouse;
	PLED_REPEAT				Led;

	SPECIAL_ACTION			Special_Action;

	/* HID datas */
	USHORT					Report_Descriptor_Size;
	UCHAR					*HID_Report_Space;
	USHORT					Size_HID_Report_Space;
	PVOID					hid_worker_thread_obj;
	KEVENT					hid_worker_wakeup_event;
	ULONG					hid_input_changed;

	UNICODE_STRING			RegPath;

} DEVICE_EXTENSION, *PDEVICE_EXTENSION;



#define	KEY_BTN			0x01
#define	KEY_KEEP		0x02
#define	KEY_RELEASE		0x04
#define	KEY_REPEAT		0x10

#pragma pack(push, 1)
static UCHAR JOY_POVVal[16] = 
{ 
	// Centered - any other occurence of '8' marks an invalid position!
	8,
	// Up
	0,
	// Right
	2,
	// Up/right
	1,
	// Down
	4, 8,
	// Down/right
	3, 8,
	// Left
	6,
	// Up/left
	7, 8, 8,
	// Down/left
	5, 8, 8, 8
};
// The POV is defined in a (more or less) funny way:
// 7 0 1
//  \|/
// 6-8-2
//  /|\
// 5 4 3
// To map the 4 semiaxes to that, let's use something like a truth table (or
// lookup table) with the input index being constructed from the 4 input
// semiaxes as bits. This results in a truth table with 16 values, of which
// only 9 are valid.
// This peculiar approach seemed to be the most flexible and easy to implement
// and debug. Thus, it would be easy to replace an 'invalid' position with an
// intelligible alternative. For example, if Up/Left/Right are pressed the
// result could be Up only (like Left and Right cancel out each other)
// instead of an invalid position...
/*! The number of buttons on the output (i.e. Windows) side */


typedef enum {
	BIND_FROM_AXE,
	BIND_FROM_BTN,

} BIND_FROM;

typedef enum {
	BIND_TO_NOBIND=0,
	BIND_TO_JOYSTICK_AXE,
	BIND_TO_JOYSTICK_BTN,
	BIND_TO_JOYSTICK_POV,
	BIND_TO_MOUSE_X,
	BIND_TO_MOUSE_Y,
	BIND_TO_MOUSE_WHEEL,
	BIND_TO_MOUSE_BTN,
	BIND_TO_KEYB,
	BIND_TO_PROFIL,
	BIND_TO_WWW,

} BIND_TO;

typedef enum {
	POV_VERT,
	POV_HORI,

} BIND_POV;

typedef enum {
	AXE_ALL=0,
	AXE_POS,
	AXE_NEG,
} SEMI_AXE;

typedef struct {

	UCHAR		NumAxe;
	BOOLEAN		Invert;
	short		DeadVal;
	short		MinVal;
	short		MaxVal;
	SEMI_AXE	AxePart;

} NAVAXE, *PNAVAXE;

typedef enum {
	PRESS_STD=0,
	PRESS_SHORT,
	PRESS_LONG,
} PRESS_TYPE;

typedef struct {

	UCHAR		NumBtn;
	BOOLEAN		Invert;
	short		FalseVal;
	short		TrueVal;

} NAVBTN, *PNAVBTN;

typedef struct {

	short		Delay;
	PRESS_TYPE	Type;

} FROM_TYPE;

typedef struct {

	UCHAR		Event;
	short		FireDelay;
	UCHAR		Code[5];

} KEY_BIND;

typedef struct {

	union {
		UCHAR		Axe;
		UCHAR		Btn;
		BIND_POV	POV;
	};

} JOY_BIND;


typedef struct {

	union {
		UCHAR		Sensi;
		UCHAR		Wheel_Speed;
		UCHAR		Btn;
	};

} MOU_BIND;

typedef struct _BIND_LIST {

	BIND_FROM	BindFrom;

	union {
		NAVAXE	FromAxe;
		NAVBTN	FromBtn;
	};

	BIND_TO		BindTo;

	union {
		JOY_BIND	Joy;
		MOU_BIND	Mou;
		KEY_BIND	Key;
		UCHAR		www;
		short		Profil_Id;
	};

	FROM_TYPE FromType;

	struct _BIND_LIST *NextBind;
	NAV_STATUS Nav;

} BIND_LIST,*PBIND_LIST;


typedef struct _PROFIL {
	short				Profil_Id; 
	WCHAR				ProfilName[50];

	short				DeadVal;

	PBIND_LIST			Bind_Liste;

	struct _PROFIL		*NextProfil;

} PROFIL,*PPROFIL;

#pragma pack(pop)
/* setting stored in registroy */

HANDLE RBC9_Open_Reg(IN PWSTR basekey,IN PWSTR subkey);
NTSTATUS RBC9_Get_Key_Info(HANDLE key,unsigned int *NbrSubKey,unsigned int *NbrValue);
NTSTATUS RBC9_Get_SubKey_Name(HANDLE key,unsigned int Num_SubKey,WCHAR *buf,ULONG bufsize);
NTSTATUS RBC9_Get_Value_Info(HANDLE key,unsigned int Num_Value,WCHAR *buf,ULONG bufsize,ULONG * Type);
NTSTATUS RBC9_Set_Data(HANDLE key, IN PWSTR name,IN ULONG Type , IN PVOID  Data,IN ULONG  DataSize);
NTSTATUS RBC9_Set_DWORD(HANDLE key , IN PWSTR name, IN LONG val);
NTSTATUS RBC9_Set_BINARY(HANDLE key , IN PWSTR name, IN PVOID  Data,IN ULONG  DataSize);
NTSTATUS RBC9_Get_Data(HANDLE key, IN PWSTR name, OUT PKEY_VALUE_PARTIAL_INFORMATION *val);
NTSTATUS RBC9_Get_DWORD(HANDLE key , IN PWSTR name, OUT PLONG val, IN ULONG def_val);
NTSTATUS RBC9_Get_STRING(HANDLE key , IN PWSTR name, OUT PWCHAR val, IN ULONG size);
NTSTATUS RBC9_Get_BINARY(HANDLE key , IN PWSTR name, OUT PVOID val, IN ULONG size);/* read report */

#define REPORT_ID_JOY			0xf1
#define REPORT_ID_KEY			0xf2
#define REPORT_ID_WWWKEY		0xf3
#define REPORT_ID_MOU			0xf4

#define REPORT_ID_CMD			0xf0
#define REPORT_ID_NAV_ID1		0x01
#define REPORT_ID_NAV_ID2		0x02
#define REPORT_ID_NAV_ID3		0x03

#define INPUT_TYPE_JOYSTICK		0x01
#define INPUT_TYPE_MOUSE		0x02
#define INPUT_TYPE_KEYBOARD		0x04
#define INPUT_TYPE_WWW			0x08
#define INPUT_TYPE_INFO			0x80
#define INPUT_TYPE_RBC_ALL		(INPUT_TYPE_JOYSTICK | INPUT_TYPE_MOUSE | INPUT_TYPE_KEYBOARD | INPUT_TYPE_WWW | INPUT_TYPE_INFO )

#define INPUT_TYPE_NAV_ID1		0x10
#define INPUT_TYPE_NAV_ID2		0x20
#define INPUT_TYPE_NAV_ID3		0x40
#define INPUT_TYPE_NAV_ALL		(INPUT_TYPE_NAV_ID1 | INPUT_TYPE_NAV_ID2 | INPUT_TYPE_NAV_ID3 )

#define INPUT_TYPE_ALL			(INPUT_TYPE_RBC_ALL | INPUT_TYPE_NAV_ALL)

#define INPUT_REPORT_NUM_JOY_AXE	8
#define INPUT_REPORT_NUM_JOY_BUTTON 8
#define INPUT_REPORT_NUM_KBD_CODE   232
#define INPUT_REPORT_NUM_WWW_CODE	16
#define INPUT_REPORT_NUM_MOU_BUTTON 5

#define KEY_BASE_MODIFIER	0xe0
#define KEY_MAX_KEY			6

#define JOY_OFFSET 360

#define MOU_MAX_VALUE 127
#define MOU_MAX_BTN	5

#define MOU_DELAY_QUICK 10
#define MOU_DELAY_LENT 1000
#define NAV_VALUE_QUICK 300
#define NAV_VALUE_LENT 2

#define NAV_MAX_VALUE 360
#define NAV_MAX_CARRE (NAV_MAX_VALUE*NAV_MAX_VALUE)
#define NAV_MAX_AXE 6
#define NAV_MAX_BTN 21

static UCHAR NAV_PACKET_LED[]		= { 0x21,0x09,0x04,0x02,0x00,0x00,0x02,0x00};
static UCHAR NAV_PACKET_INIT[]		= { 0x21,0x09,0x06,0x03,0x00,0x00,0x02,0x00};

static UCHAR NAV_PACKET_DESCRIPTOR[]		= { 0x81,0x06,0x00,0x22,0x00,0x00,0x0a,0x01};

#pragma pack(push, 1)


typedef struct _CONTROLLER_SPACENAV_INPUT_REPORT {

	UCHAR report_id;
	union {
		short Axe[3];
		UCHAR Btn[6];
	};

} CONTROLLER_SPACENAV_INPUT_REPORT, *PCONTROLLER_SPACENAV_INPUT_REPORT;

typedef struct _CONTROLLER_SPACENAV_TRAME {

	CONTROLLER_SPACENAV_INPUT_REPORT Trame[3];

} CONTROLLER_SPACENAV_TRAME, *PCONTROLLER_SPACENAV_TRAME;

typedef struct _CONTROLLER_JOY_INPUT_REPORT {
	UCHAR report_id;            /* Report ID: 1 */

	union {
		struct {
			SHORT x;            /* X:  0x00 - 0xff */
			SHORT y;            /* Y:  0x00 - 0xff */
			SHORT z;            /* Z:  0x00 - 0xff */
			SHORT rx;           /* RX: 0x00 - 0xff */
			SHORT ry;           /* RY: 0x00 - 0xff */
			SHORT rz;           /* RZ: 0x00 - 0xff */
			SHORT slider;       /* SL: 0x00 - 0xff */
			SHORT slider2;      /* SL: 0x00 - 0xff */
		//	SHORT throttle;     /* TH: 0x00 - 0xff */
		};

		struct {
			SHORT axis[INPUT_REPORT_NUM_JOY_AXE];      /* x, y, z, rx, ry, yz, slider, throttle */
		};
	};

	UCHAR Pov : 4;				/* H1: 0x00 - 0x07 */
	UCHAR Pov_Aling : 4;        /* Padding */

	UCHAR button;				/* BN: 0x00/0x01 */

} CONTROLLER_JOY_INPUT_REPORT;

typedef struct _CONTROLLER_KBD_INPUT_REPORT {
	UCHAR report_id;           

	UCHAR Modifier;

	UCHAR keys[6]; 

} CONTROLLER_KBD_INPUT_REPORT;


typedef struct _CONTROLLER_WWW_INPUT_REPORT {
	UCHAR report_id;            /* Report ID: 2 */

	UCHAR keys[(INPUT_REPORT_NUM_WWW_CODE + 7) / 8]; 
} CONTROLLER_WWW_INPUT_REPORT;

typedef struct _CONTROLLER_MOU_INPUT_REPORT {
	UCHAR report_id;            /* Report ID: 3 */

	CHAR x;                     /* x:     0x81 - 0x7f */
	CHAR y;                     /* y:     0x81 - 0x7f */
	CHAR wheel;                 /* wheel: 0x81 - 0x7f */

	UCHAR button;				/* 5 buttons */
} CONTROLLER_MOU_INPUT_REPORT;

typedef struct _CONTROLLER_INFO_INPUT_REPORT {
	UCHAR	report_id;           

	UCHAR	Ctrl;
	short	Profil_Id; 

} CONTROLLER_INFO_INPUT_REPORT;

typedef struct _CONTROLLER_INPUT_REPORT {
	CONTROLLER_JOY_INPUT_REPORT		joy;
	CONTROLLER_KBD_INPUT_REPORT		kbd;
	CONTROLLER_WWW_INPUT_REPORT		www;
	CONTROLLER_MOU_INPUT_REPORT		mou;
	CONTROLLER_INFO_INPUT_REPORT	Info;
	CONTROLLER_SPACENAV_TRAME		SpaceNav;

} CONTROLLER_INPUT_REPORT;

typedef struct _CONTROLLER_CMD_REPORT
{
	UCHAR command;
	union {
		UCHAR InfoByte; 
		short ProfilNum;
	};

} CONTROLLER_CMD_REPORT;

typedef struct _CONTROLLER_OUTPUT_REPORT
{
	UCHAR report_id;            /* Report ID: 1 */

	union {
		UCHAR OriByte[7]; 
		CONTROLLER_CMD_REPORT Cmd;
	};


} CONTROLLER_OUTPUT_REPORT, *PCONTROLLER_OUTPUT_REPORT;

typedef struct _RAW_INPUT {
	UCHAR ReportId;
	union {
		struct {
			SHORT Axe[3];
		};
		struct {
			UCHAR Btn[6]; 
		};
	};

} RAW_INPUT, *PRAW_INPUT;

typedef struct _RAW_OUTPUT {
	UCHAR ReportId;
	UCHAR InfoByte;
} RAW_OUTPUT, *PRAW_OUTPUT;


typedef struct _MOU_REPEAT
{
	ULONGLONG				next_time;
	ULONGLONG				wheel_time;
	ULONGLONG				wheel_wait;
	char					wheel_val;

} MOU_REPEAT;

typedef struct _LED_REPEAT
{
	BOOLEAN					On;
	ULONGLONG				first_time;
	ULONGLONG				next_time;
	ULONGLONG				TimeOn;
	ULONGLONG				TimeOff;
	ULONGLONG				HowLong;

	struct _LED_REPEAT		*NextLed;

} LED_REPEAT, *PLED_REPEAT;

typedef struct _SPECIAL_ACTION
{
	BOOLEAN			Running;
	ULONGLONG		MinTime;
	ULONGLONG		Start_Detect;
	ULONGLONG		Time_Action;

} SPECIAL_ACTION;

typedef struct _KEY_FLAG {

	UCHAR		Event;
	short		Fire_Delay;
	ULONGLONG	Last_Fire;

}KEY_FLAG;

typedef struct _KEYB_STATUS {

	KEY_FLAG	Key[INPUT_REPORT_NUM_KBD_CODE];	

} KEYB_STATUS;

typedef struct _NAV_STATUS {
	BOOLEAN		Last_On;
	short		Last_Val;
	ULONGLONG	Last_Press;
	ULONGLONG	Last_Release;
} NAV_STATUS;


#pragma pack(pop)#include <ntifs.h>
#include <ntddk.h>

#include <wdm.h>
#include <usbdrivr.h>
#include <HIDPORT.H>

#include "buildnumber.h"
#include "RBC9-Report.h"
#include "RBC9-Profil.h"
#include "RBC9-Device.h"
#include "RBC9-Registre.h"

#define PAGEDCODE code_seg("PAGE")
#define LOCKEDCODE code_seg()

#define RBC9_COMPLETE_REQUEST(irp, info, status, pri) \
  (irp)->IoStatus.Information = (info); \
  (irp)->IoStatus.Status = (status); \
  IoCompleteRequest((irp), (pri));

#define DBG_OUT(_x_)						\
    KdPrint(_x_);								\
  KdPrint(("\n"));

#define DBG_INFO(_x_)						\
    KdPrint(_x_);							

#define DBG_ENTER(_x_)						\
  KdPrint(("> Enter: %s: ", __FUNCTION__));   \
   KdPrint(_x_);								\
  KdPrint(("\n"));

#define DBG_LEAVE(_x_)						\
  KdPrint(("> Leave: %s: ", __FUNCTION__));   \
  KdPrint(_x_);								\
  KdPrint(("\n"));



NTSTATUS RBC9_DispatchCreateClose(
	IN PDEVICE_OBJECT		DeviceObject,
	IN PIRP					Irp
	);

VOID RBC9_DriverUnload(
	IN PDRIVER_OBJECT		DriverObject 
	);

NTSTATUS RBC9_AddDevice(
	IN PDRIVER_OBJECT DriverObject,
	IN PDEVICE_OBJECT func_dev_obj
	);

NTSTATUS RBC9_DispatchPnp(
	IN PDEVICE_OBJECT		dev_obj,
	IN PIRP irp
	);

NTSTATUS RBC9_DispatchPower(
	IN PDEVICE_OBJECT pDev_obj, 
	IN PIRP pIrp
	);

NTSTATUS RBC9_DispatchIntDevice(
	IN PDEVICE_OBJECT pDev_obj,
	IN PIRP pIrp
	);

NTSTATUS RBC9_DispatchDevice(
	IN PDEVICE_OBJECT pFdo, 
	IN PIRP pIrp
	);

NTSTATUS RBC9_DispatchSystem(
	IN PDEVICE_OBJECT pFdo, 
	IN PIRP pIrp
	);

NTSTATUS RBC9_IncRequestCount(
	IN PDEVICE_EXTENSION pDevExt
	);

VOID RBC9_DecRequestCount(
	IN PDEVICE_EXTENSION pDevExt
	);


// RBC9-Pnp.c

NTSTATUS RBC9_pnp_complete(
	IN PDEVICE_OBJECT pDev_obj, 
	IN PIRP pIrp,
	IN PVOID ctxt);

NTSTATUS RBC9_pnp_start(
	IN PDEVICE_OBJECT pDev_obj,
	IN PIRP pIrp
	);

NTSTATUS RBC9_device_start(
	IN PDEVICE_OBJECT pDev_obj
	);

NTSTATUS RBC9_pnp_stop(
	IN PDEVICE_OBJECT pDev_obj,
	IN PIRP pIrp
	);

NTSTATUS RBC9_pnp_surprise_remove(
	IN PDEVICE_OBJECT pDev_obj,
	IN PIRP pIrp
	);

NTSTATUS RBC9_pnp_remove(
	IN PDEVICE_OBJECT pDev_obj,
	IN PIRP pIrp
	);

NTSTATUS RBC9_device_remove(
	IN PDEVICE_OBJECT pDev_obj
	);

NTSTATUS RBC9_pnp_capabilities(
	IN PDEVICE_OBJECT pDev_obj,
	IN PIRP pIrp
	);

// RBC9-IOCTL.c

NTSTATUS RBC9_ioctl_get_dev_desc(
	IN PDEVICE_OBJECT pDev_obj,	
	IN PIRP pIrp
	);

NTSTATUS RBC9_ioctl_get_dev_attr(
	IN PDEVICE_OBJECT pDev_obj,	
	IN PIRP pIrp
	);

NTSTATUS RBC9_ioctl_get_rep_desc(
	IN PDEVICE_OBJECT pDev_obj,	
	IN PIRP pIrp
	);

NTSTATUS RBC9_ioctl_read_rep(
	IN PDEVICE_OBJECT pDev_obj,	
	IN PIRP pIrp
	);

NTSTATUS RBC9_ioctl_write_rep(
	IN PDEVICE_OBJECT pDev_obj,	
	IN PIRP pIrp
	);

VOID RBC9_notify_input_report_change(
	IN PDEVICE_OBJECT pDev_obj
	);

VOID RBC9_notify_input_report_stop(
	IN PDEVICE_OBJECT pDev_obj
	);

// RBC9-USB.c

NTSTATUS RBC9_usb_start(
	IN PDEVICE_OBJECT pDev_obj
	);

NTSTATUS RBC9_usb_remove(
	IN PDEVICE_OBJECT pDev_obj
	);

static NTSTATUS RBC9_usb_reset(
	IN PDEVICE_OBJECT Dev_obj);

static NTSTATUS RBC9_usb_get_port_status(
	IN PDEVICE_OBJECT pDev_obj,
	OUT ULONG *port_status
	);

static NTSTATUS RBC9_usb_call(
	IN PDEVICE_OBJECT pDev_obj, 
	IN ULONG ioctl_code,
    IN PVOID arg1,
	IN PVOID arg2
	);

static NTSTATUS RBC9_usb_reset_port(
	IN PDEVICE_OBJECT pDev_obj
	);

static NTSTATUS RBC9_usb_get_dev_desc(
	IN PDEVICE_OBJECT pDev_obj
	);

static NTSTATUS RBC9_usb_select_conf(
	IN PDEVICE_OBJECT pDev_obj
	);

static NTSTATUS RBC9_usb_get_conf_desc(
	IN PDEVICE_OBJECT pDev_obj,
    OUT PUSB_CONFIGURATION_DESCRIPTOR *conf_desc,
    OUT ULONG *size,
    IN UCHAR conf_idx);


static NTSTATUS RBC9_usb_get_hid_desc(
	IN PDEVICE_OBJECT pDev_obj
	);


static VOID RBC9_usb_worker(
	IN PVOID ctxt);

NTSTATUS RBC9_usb_get_interrupt_transfer(
	IN PDEVICE_OBJECT pDev_obj, 
	IN PVOID buf, 
	ULONG *buf_size);

NTSTATUS RBC9_usb_put_interrupt_transfer(
	IN PDEVICE_OBJECT pDev_obj, 
	IN PVOID buf, 
	ULONG *buf_size);

NTSTATUS RBC9_usb_put_control_transfer(
	IN PDEVICE_OBJECT pDev_obj, 
	IN PVOID buf, 
	ULONG *buf_size,
	IN PVOID packet
	);
NTSTATUS RBC9_usb_get_control_transfer(
	IN PDEVICE_OBJECT pDev_obj, 
	IN PVOID buf, 
	ULONG *buf_size,
	IN PVOID packet
	);

static NTSTATUS RBC9_usb_interrupt_transfer(
	IN PDEVICE_OBJECT pDev_obj,
    IN PVOID buf, 
	ULONG *buf_size,
    USBD_PIPE_HANDLE pipe, 
	ULONG flags);

static NTSTATUS RBC9_usb_control_transfer(
	IN PDEVICE_OBJECT pDev_obj,
    IN PVOID buf, 
	ULONG *buf_size,
    USBD_PIPE_HANDLE pipe, 
	ULONG flags,
	IN PVOID packet);

// RBC9-Hid.c

NTSTATUS RBC9_hid_start(
	IN PDEVICE_OBJECT pDev_obj);

NTSTATUS RBC9_hid_remove(
	IN PDEVICE_OBJECT pDev_obj
	);

NTSTATUS RBC9_hid_get_rep_desc(
	IN PDEVICE_OBJECT pDev_obj, 
	OUT UCHAR *buf, 
	OUT ULONG *size);

NTSTATUS RBC9_hid_read_rep(
	IN PDEVICE_OBJECT pDev_obj, 
	OUT UCHAR *buf, 
	OUT ULONG *size);

NTSTATUS RBC9_hid_write_rep(
	IN PDEVICE_OBJECT pDev_obj,
	IN UCHAR *buf, 
	IN ULONG *size, 
	IN UCHAR id);

static VOID RBC9_hid_worker(
	IN PVOID ctxt
	);

static VOID RBC9_hid_generate_raw_output(
	PCONTROLLER_OUTPUT_REPORT out_state,
	PRAW_OUTPUT raw_out
	);

NTSTATUS RBC9_nav_led(
	IN PDEVICE_OBJECT pDev_obj,
	BOOLEAN Led
	);

NTSTATUS RBC9_nav_calibrate(
	IN PDEVICE_OBJECT pDev_obj
	);


NTSTATUS RBC9_nav_init(
	IN PDEVICE_OBJECT pDev_obj
	);



// RBC9-Profil.c

void RBC9_Wait(
	short MilliSec);

VOID RBC9_InitState(
	IN PDEVICE_OBJECT pDev_obj);

VOID RBC9_process_raw_input(
	IN PDEVICE_OBJECT pDev_obj
	);


VOID RBC9_Delete_Profil(
	IN PDEVICE_OBJECT pDev_obj
	);

PPROFIL RBC9_Select_Profil(
	IN PDEVICE_OBJECT pDev_obj,
	short Profil_Id
	);

BOOLEAN RBC9_Profil_Exist(
	IN PDEVICE_OBJECT pDev_obj,
	short Profil_Id
	);

VOID RBC9_Clear_KeyB_Buffer(
	IN PDEVICE_OBJECT pDev_obj,
	BOOLEAN ClearKeep
	);

// RBC9-Led.c

VOID RBC9_Led_Queue_Add(IN PDEVICE_OBJECT pDev_obj,int HowLong,int TimeOn,int TimeOff);
VOID RBC9_Led_Queue_Delete(IN PDEVICE_OBJECT pDev_obj);
VOID RBC9_Led_Clignote(IN PDEVICE_OBJECT pDev_obj);

VOID RBC9_SEQ_Change_Profil(IN PDEVICE_OBJECT pDev_obj);
VOID RBC9_SEQ_Init_HID(IN PDEVICE_OBJECT pDev_obj);
VOID RBC9_SEQ_Special_Action(IN PDEVICE_OBJECT pDev_obj);
VOID RBC9_SEQ_Special_Action_Fin(IN PDEVICE_OBJECT pDev_obj);




